Pagini recente » Cod sursa (job #1622047) | Cod sursa (job #1259383) | Cod sursa (job #2323468) | Cod sursa (job #2588044) | Cod sursa (job #855541)
Cod sursa(job #855541)
#include <fstream>
#include <iostream>
#include <cstdlib>
#define MAXN 3000001
using namespace std;
unsigned int vec[MAXN];
template<typename T>
void do_partition(T vec[], int& left, int& right, const T& pivotVal)
{
while (left < right)
{
while (vec[left] < pivotVal) ++left;
while (pivotVal < vec[right]) --right;
if (left <= right)
{
swap(vec[left], vec[right]);
++left;
--right;
}
}
}
template<typename T>
int find_nth_element(T vec[], int left, int right, int n)
{
if (left >= right) return vec[left];
int pivotPos = left + (rand() % (right - left));
int newLeft = left;
int newRight = right;
do_partition(vec, newLeft, newRight, vec[pivotPos]);
if (n <= newRight)
{
return find_nth_element(vec, left, newRight, n);
}
else if (n >= newLeft)
{
return find_nth_element(vec, newLeft, right, n);
}
return vec[pivotPos];
}
template <typename T>
int nth_element(T vec[], int sizeVec, int n)
{
return find_nth_element(vec, 0, sizeVec - 1, n);
}
int main()
{
int n, k;
fstream fin("sdo.in", fstream::in);
fstream fout("sdo.out", fstream::out);
fin >> n >> k;
for (int i=0; i<n; ++i)
{
fin >> vec[i];
//cout << vec[i] << " ";
}
//cout << endl;
fout << nth_element(vec, n, k-1) << endl;
return 0;
}