Pagini recente » Cod sursa (job #1814348) | Cod sursa (job #3258608) | Cod sursa (job #3225260) | Cod sursa (job #1667063) | Cod sursa (job #855542)
Cod sursa(job #855542)
#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)
{
int pivotPos = left + (rand() % (right - left + 1));
int newLeft = left;
int newRight = right;
do_partition(vec, newLeft, newRight, vec[pivotPos]);
if (n == pivotPos) return vec[pivotPos];
if (n <= newRight)
{
return find_nth_element(vec, left, newRight, n);
}
else
{
return find_nth_element(vec, newLeft, right, n);
}
}
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;
}