Cod sursa(job #2433816)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 29 iunie 2019 11:23:10
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("sdo.in");
ofstream fout("sdo.out");

int n, k, v[3000005];

int sdo(int st, int dr)
{
    if (st <= dr)
    {
        int random_index_pivot = st + rand() % (dr - st + 1);
        int pivot = v[random_index_pivot];
        int index = st;
        swap(v[dr], v[random_index_pivot]);
        for (int i = st; i < dr; ++i)
        {
            if (v[i] < pivot)
            {
                swap(v[i], v[index++]);
            }
        }
        swap(v[dr], v[index]);
        if (index == k)
            return v[index];
        if (index > k)
        {
            sdo(st, index - 1);
        }
        else
        {
            sdo(index + 1, dr);
        }
    }
}

int main()
{
    srand(time(0));
    fin >> n >> k;
    for (int i = 1; i <= n; ++i)
    {
        fin >> v[i];
    }
    fout << sdo(1, n);
    fin.close();
    fout.close();
}