Cod sursa(job #2607787)

Utilizator RobertLearnsCDragomir Robert. RobertLearnsC Data 30 aprilie 2020 10:48:23
Problema Statistici de ordine Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 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;
}

void celMaiSort(int left, int right, int nthElement) {
    if(left >= right) {
        return;
    }
    int middle = partition(left, right);
    if(nthElement < middle) {
        celMaiSort(left, middle - 1, nthElement);
    } else if(nthElement > middle) {
        celMaiSort(middle + 1, right, nthElement);
    }
}

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

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