Cod sursa(job #1008147)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 10 octombrie 2013 13:00:06
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>

#define Nmax 1000001

using namespace std;

int a[Nmax];
int n,k;

int partitioning(int left, int right)
{
	int pivot = a[left + rand()%(right-left+1)];
	int i = left, j = right;
	while (1)
	{
		while (a[i] < pivot) ++i;
		while (a[j] > pivot) --j;
		if (i < j)
		{
			int aux = a[i];
			a[i] = a[j];
			a[j] = aux;
		}
		else return j;
		++i;
		--j;
	}
	return 0;
}

void select(int left, int right, int k)
{
	if (left == right)
		return;

	int v = partitioning(left,right);
	int dist = (v-left)+1;
	
	if (k <= dist)
		select(left, v, k);
	else select(v+1, right, v-dist);
}

int main()
{
	freopen("sdo.in","r",stdin);
	freopen("sdo.out","w",stdout);
	srand(time(NULL));
	scanf("%d %d",&n,&k);
	for (int i = 0; i < n; ++i)
	{
		scanf("%d",&a[i]);
	}

	select(0,n-1,k-1);
	printf("%d\n", a[k-1]);


	return 0;
}