Cod sursa(job #2607793)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 30 aprilie 2020 10:52:00
Problema Statistici de ordine Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
using namespace std;

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

int  n, v[3000005], nthElement;

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

int celMaiSort(int left, int right, int nthElement)
{
    if (nthElement > 0 && nthElement <= right - left + 1) {
        int pos = partition(left, right);
        if (pos - left == nthElement - 1) {
            return v[pos];
        }
        if (pos - left > nthElement - 1) {
            return celMaiSort(left, pos - 1, nthElement);
        }

        return celMaiSort(pos + 1, right, nthElement - pos + left - 1);
    }
}

int main() {
    in >> n >> nthElement;
    for(int i = 0; i < n; ++i) {
        in >> v[i];
    }

    celMaiSort(0, n - 1, nthElement);
    out << v[nthElement - 1];
}