Cod sursa(job #3345639)

Utilizator fmi-studentnu sunt de acord fmi-student Data 10 martie 2026 15:44:51
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#include <vector>
#include <time.h>

int partition(std::vector<int>& v, int low, int high) {
    int pivot = (rand() % (high + 1 - low)) + low;
    std::swap(v[pivot], v[high]);
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (v[j] < v[high]) {
            ++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() {
    srand(time(0));
    std::ifstream read("sdo.in");
    int k, n;
    read >> n >> k;
    --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;
}