Cod sursa(job #3345633)

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

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 v[high];
        
    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 >> n >> k;
    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() - 1, k);
    out.close();
    return 0;
}