Cod sursa(job #3345631)

Utilizator fmi-studentnu sunt de acord fmi-student Data 10 martie 2026 15:28:30
Problema Statistici de ordine Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>

int partition(std::vector<int>& v, int low, int high) {
    int pivot = v[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (v[j] < pivot) {
            ++i;
            std::swap(v[j], v[i]);
        }
    }

    std::swap(v[i + 1], v[high]);
    return i + 1;
}

int quickselect(std::vector<int>& v, int low, int high, int k) {
    if (low >= high)
        return -1;
        
    int pivot = partition(v, low, high);

    if (pivot == k) 
        return v[pivot];
    
    if (pivot > k) 
        return quickselect(v, pivot + 1, high, k);

    return quickselect(v, low, pivot - 1, k);
}

int main() {
    std::ifstream read("sdo.in");
    int k, n;
    read >> k >> n;
    std::vector<int> v;
    v.reserve(n);
    while (n--) {
        int temp;
        read >> temp;
        v.push_back(temp);
    }
    read.close();
    std::ofstream out("sdo.out");
    out << quickselect(v, 0, v.size(), k);
    out.close();
    return 0;
}