Pagini recente » Cod sursa (job #1136969) | Cod sursa (job #1284613) | Cod sursa (job #1522264) | Cod sursa (job #1026446) | Cod sursa (job #855570)
Cod sursa(job #855570)
#include <fstream>
#include <iostream>
#include <cstdlib>
#define MAXN 3000001
using namespace std;
template<typename T>
int 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;
}
}
return (left + right)/2;
}
template<typename T>
void find_nth_element(T vec[], int left, int right, int n)
{
int pivotPos = (right+left)/2;//(rand() % (right - left + 1));
if (left >= right) return;
pivotPos = do_partition(vec, left, right, vec[pivotPos]);
if (n == pivotPos)
{
return;
}
if (n < pivotPos)
{
find_nth_element(vec, left, pivotPos, n);
}
else
{
find_nth_element(vec, pivotPos, right, n);
}
}
template <typename T>
int nth_element(T vec[], int sizeVec, int n)
{
find_nth_element(vec, 0, sizeVec - 1, n-1);
return vec[n-1];
}
int main()
{
int n, k;
unsigned long *vec;
fstream fin("sdo.in", fstream::in);
fstream fout("sdo.out", fstream::out);
fin >> n >> k;
vec = new unsigned long [n+1];
for (int i=0; i<n; ++i)
{
fin >> vec[i];
//cout << vec[i] << " ";
}
//cout << endl;
fout << nth_element(vec, n, k) << endl;
return 0;
}