Cod sursa(job #3347322)

Utilizator mitoceanuci@gmail.comMitoceanu Ciprian [email protected] Data 16 martie 2026 11:33:12
Problema Statistici de ordine Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
using namespace std;

int partition(int v[], int left, int right)
{
    int pivot = left + rand() % (right - left + 1);
    swap(v[pivot], v[right]);

    int storeIndex = left;
    for (int j = left; j <= right - 1; j++)
    {
        if (v[j] <= v[right])
        {
            swap(v[storeIndex], v[j]);
            storeIndex++;
        }
    }
    swap(v[right], v[storeIndex]);

    return storeIndex;
}
int v[3000001];

int main()
{
    ifstream fin("file.in");
    ofstream fout("file.out");

    int n, k;

    fin >> n >> k;

    for (int i = 1; i <= n; i++)
    {
        fin >> v[i];
    }
    int left = 1, right = n;

    while (left <= right)
    {
        int storeIndex = partition(v, left, right);
        if (storeIndex == k)
        {
            fout << v[storeIndex];
            return 0;
        }
        else if (storeIndex < k)
        {
            left = storeIndex + 1;
        }
        else
        {
            right = storeIndex - 1;
        }
    }
    return 0;
}