Cod sursa(job #1681894)

Utilizator Ruben2015Parvu Ruben Ruben2015 Data 9 aprilie 2016 19:52:19
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<stdio.h>
#include<algorithm>
#include<ctime>
using namespace std;
int v[3000005], n, k;
void citire()
{
    int i;

    scanf("%d%d", &n, &k);

    for(i = 1; i <= n; i++)
        scanf("%d", &v[i]);
}



int part(int low, int high)
{
    int i, j, pivot;

    pivot = v[low + rand() % (high - low)];
    i = low - 1;
    j = high + 1;

     while (i <= j)
    {
        i++;
        j--;

        while (v[i] < pivot)
            i++;

        while (v[j] > pivot)
            j--;

        if (i < j)
            swap(v[i], v[j]);
         else
            return j;
    }
}



void quicksort(int low, int high)
{
    int pivot;

    if(low < high)
    {
        pivot = part(low, high);

        if(k <= pivot)
            quicksort(low, pivot);
        else
            if(k > pivot)
                quicksort(pivot + 1, high);
    }
}


int main()
{
    freopen("sdo.in", "r", stdin);
    freopen("sdo.out", "w", stdout);

    srand(time(0));

    citire();

    quicksort(1, n);

    printf("%d", v[k]);

    return 0;
}