Pagini recente » Cod sursa (job #2639780) | Cod sursa (job #1729401) | Cod sursa (job #1844079) | Cod sursa (job #214312) | Cod sursa (job #855546)
Cod sursa(job #855546)
#include <fstream>
#include <iostream>
#include <cstdlib>
#define MAXN 3000001
using namespace std;
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 + (right - left)/2;//(rand() % (right - left + 1));
int newLeft = left;
int newRight = right;
do_partition(vec, newLeft, newRight, vec[pivotPos]);
if (n == (newRight + newLeft) / 2)
{
return vec[(newRight + newLeft) / 2];
}
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;
int *vec;
fstream fin("sdo.in", fstream::in);
fstream fout("sdo.out", fstream::out);
fin >> n >> k;
vec = new int[n+1];
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;
}