Cod sursa(job #635280)

Utilizator cristianalex81Cristian Alexandru cristianalex81 Data 19 noiembrie 2011 03:18:13
Problema Statistici de ordine Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <ctime>
#define dim 3000001

using namespace std;

int n,k;
int a[dim];

int split(int l, int r)
{
    int temp,i=l,j=r;
    int p=(l+r)/2;
    while (1)
    {
        while((a[i]<a[p])&&(p>=i))//while numbers are lower and i've not passed the piviot
            i++;
        while((a[j]>a[p])&&(p<=j))//while numbers are higher and i'be not passed the piviot
            j--;
        if (i<j)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            if(i==p)
                p=j,i++; //position of the pivot has changed increment only i
            else
                if(j==p)
                    p=i,j--; //position of the pivot has changed decrement only j
                else
                    i++,j--; //increment i, decrement j
        }
        else
            return p;
    }
}

int quick_sort(int l, int r)
{
    int p;
    if(l<r)
    {
        p = split(l,r);
        if (p==k)
            return p;
        else
        {
            if (p>k)
                return quick_sort(l,p-1);
            else
                return quick_sort(p+1,r);
        }
    }
    return 0;
}

int main()
{
    ifstream f ("sdo.in");
    ofstream g ("sdo.out");
    int i;
    f>>n,f>>k,k--;
    for (i=0;i<n;i++)
        f>>a[i];
    i = quick_sort(0,n-1);
    g<<a[i]<<"\n";
    return 0;
}