Pagini recente » Cod sursa (job #2221187) | Cod sursa (job #2670645) | Cod sursa (job #2040978) | Cod sursa (job #2378731) | Cod sursa (job #1104090)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
using namespace std;
void print(vector<int> V) {
for (vector<int>::iterator it=V.begin(); it!=V.end(); ++it)
cout << *it << " ";
cout << endl;
}
int Partition(vector<int>& V, int left, int right, int pivot) {
int high = right;
int X = V[pivot];
int i;
for (i=left; i<high; ) {
if (V[i] > X) {
swap(V[i], V[high]);
high --;
} else if (V[i] == X) {
swap(V[i], V[i+1]);
} else {
i ++;
}
}
return i;
}
int QuickSelect(vector<int>& V, int target, int left, int right) {
int pivot = rand() % (right - left + 1) + left;
int newPivot = Partition(V, left, right, pivot);
//cout << pivot << " " << newPivot << endl;
//print(V);
if (newPivot == target) {
return V[target];
} else if (newPivot < target) {
return QuickSelect(V, target, newPivot + 1, right);
} else {
return QuickSelect(V, target, left, newPivot-1);
}
}
int main() {
srand(time(0));
ifstream in("sdo.in");
ofstream out("sdo.out");
int N, K;
vector<int> V;
in >> N >> K;
while (N--) {
int x;
in >> x;
V.push_back(x);
}
out << QuickSelect(V, K - 1, 0, V.size() - 1) << "\n";
return 0;
}