Cod sursa(job #3349547)

Utilizator alexlazuLazureanu Alexandru Ioan alexlazu Data 31 martie 2026 15:36:36
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

ifstream in("sdo.in");
ofstream out("sdo.out");

#define cin in
#define cout out

int n, k;
vector<int> v;

// Pass k as a parameter to avoid global variable side-effects
int partition(int stanga, int dreapta, int k)
{
    // Base case: if the range has only one element
    if (stanga == dreapta)
        return v[stanga];

    int mij = stanga + (dreapta - stanga) / 2;
    std::swap(v[mij], v[dreapta]); // Move pivot to end

    int poz = stanga;
    for (int i = stanga; i < dreapta; i++)
    {
        if (v[i] <= v[dreapta]) {
            std::swap(v[i], v[poz]);
            poz++;
        }
    }
    std::swap(v[poz], v[dreapta]); // Move pivot to its final place

    // Logic Check:
    if (poz == k)
        return v[poz];
    else if (k > poz)
        // Search the right side, k stays the same
        return partition(poz + 1, dreapta, k);
    else
        // Search the left side, k stays the same
        return partition(stanga, poz - 1, k);
}

int main()
{
    cin >> n >> k;
    for (int i = 0, x; i < n; i++)
    {
        cin >> x;
        v.push_back(x);
    }
    k = k - 1;
    // alegem un subarray
    // luam un pivot (el de la mijloc)
    // partitionam array-ul bazat pe marimea pivotului
    int rez = partition(0, n - 1 , k);
    cout << rez;
    return 0;
}