Pagini recente » Cod sursa (job #2289946) | Cod sursa (job #74639) | Cod sursa (job #738448) | Cod sursa (job #596537) | Cod sursa (job #796657)
Cod sursa(job #796657)
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
inline static int ChoosePivot(int start, int end)
{
return start + std::rand()%(end-start);
}
void Partition(vector<int>& vec, int& start, int& end, int pivotValue)
{
while (start < end)
{
while (vec[start] < pivotValue)
{
start++;
}
while (pivotValue < vec[end])
{
end--;
}
if (start <= end)
{
swap(vec[start], vec[end]);
start++;
end--;
}
}
}
void nth_element_(vector<int>& vec, int start, int end, int nth)
{
if (start < end)
{
int pivot = ChoosePivot(start, end);
int new_start = start;
int new_end = end;
Partition(vec, new_start, new_end, vec[pivot]);
if (nth <= new_end)
{
nth_element_(vec, start, new_end, nth);
}
else
{
nth_element_(vec, new_start, end, nth);
}
}
}
int main()
{
int n, nth;
vector<int> vec;
fstream fin("sdo.in", fstream::in);
fstream fout("sdo.out", fstream::out);
fin >> n >> nth;
//cout << n << " " << nth << endl;
vec.resize(n);
for (int i=0; i<n; ++i)
{
fin >> vec[i];
//cout << vec[i] << " ";
}
//cout << endl;
nth_element_(vec, 0, n-1, nth-1);
fout << vec[nth-1] << endl;
fin.close();
fout.close();
return 0;
}