Pagini recente » Cod sursa (job #3318894) | Cod sursa (job #975452) | Cod sursa (job #3314941) | Cod sursa (job #359608) | Cod sursa (job #3347153)
// Quick select implementation, O(n) time complexity, O(n^2) worst case
// Link to pbinfo solution: https://www.pbinfo.ro/detalii-evaluare/63528113
#include <iostream>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
ifstream fin("sdo.in");
ofstream fout("sdo.out");
unsigned long long int quick_select(vector<unsigned long int> &a, unsigned long int &n, unsigned long int &k, unsigned long int l){
unsigned long int pivot = l + ( rand() % ( n-l ) );
swap(a[n-1], a[pivot]);
pivot = n-1;
unsigned long int poz = l;
for(unsigned long int i=l; i<pivot; i++){
if(a[i] < a[pivot]){
swap(a[i], a[poz]);
poz++;
}
}
swap(a[poz], a[pivot]);
if(poz == k-1)
return a[poz];
else if(poz < k-1)
return quick_select(a, n, k, poz+1);
else return quick_select(a, poz, k, l);
return -1;
}
int main(){
unsigned long int n, val, k;
fin>>n>>k;
if(k > n){
cout<<"K bigger than the number of elements in the array.";
return 1;
}
vector<unsigned long int> a;
a.reserve(n+1);
for(unsigned long int i=0; i<n; i++){
fin>>val;
a.push_back(val);
}
fout<<quick_select(a, n, k, 0);
return 0;
}