Cod sursa(job #2076383)

Utilizator dariusdariusMarian Darius dariusdarius Data 26 noiembrie 2017 15:01:38
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <algorithm>
#include <fstream>
#include <iostream>
using namespace std;

const int MAX_N = 3000005;

int a[MAX_N];

void QuickSortKthElement(int left, int right, int k) {
    if (left >= right) {
        return;
    }
    swap(a[left], a[left + rand() % (right - left + 1)]);
    int i = left, j = right;
    while (i < j) {
        if (a[i] > a[i + 1] || (a[i] == a[i + 1] && rand() % 2)) {
            swap(a[i], a[i + 1]);
            ++ i;
        } else {
            swap(a[i + 1], a[j]);
            -- j;
        }
    }
    if (k < i) {
        QuickSortKthElement(left, i - 1, k);
    }
    if (k > i) {
        QuickSortKthElement(i + 1, right, k);
    }
}

int main() {
    ifstream cin("sdo.in");
    ofstream cout("sdo.out");
    int n, k;
    cin >> n >> k;
    for (int i = 1; i <= n; ++ i) {
        cin >> a[i];
    }
    QuickSortKthElement(1, n, k);
    cout << a[k] << "\n";
    return 0;
}