Pagini recente » Cod sursa (job #1216574) | Cod sursa (job #613727) | Cod sursa (job #2417157) | Cod sursa (job #405819) | Cod sursa (job #1367570)
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
ifstream in("sdo.in");
ofstream out("sdo.out");
int N, K;
int M[3000001];
void show()
{
for(int i = 1; i <= N; i++)
{
cout << M[i] << " ";
}
cout << "\n";
}
// partitionam matricea M dupa valoarea refValue incepand cu indexul start
// si returneaza numarul de ordine al pivotului ales la intamplare relativ
// la interval
int random_partition (int start, int stop){
int pivot = M[stop];
int i = start - 1, j;
for(j = start; j < stop; j++)
{
if(M[j] <= pivot) {
i = i + 1;
swap(M[i], M[j]);
}
}
swap(M[i + 1], M[stop]);
return (i + 1);
}
// selecting the ith number in ordered size form interval form start to final
int randomized_selection(int start_position, int final_position, int ith)
{
if(start_position == final_position) {
return M[start_position];
}
int q = random_partition(start_position, final_position);
int k = q - start_position + 1;
if(ith == k) {
return M[q];
} else if(ith < k) {
return randomized_selection(start_position, q - 1, ith);
} else {
return randomized_selection(q + 1, final_position, ith - k);
}
}
int main()
{
in >> N;
in >> K;
for(int i = 1; i <= N; i++)
{
in >> M[i];
}
out << randomized_selection(1, N, K);
return 0;
}