Cod sursa(job #481523)

Utilizator ilincaSorescu Ilinca ilinca Data 31 august 2010 20:11:46
Problema Statistici de ordine Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>

#define nmax 3000005

int n, k, a [nmax];

int partitionare (int st, int dr)
{
	int i=st-1, j=dr+1, piv=a [st+rand()%(dr-st)], aux;
	do
	{	
		do {++i;} while (a [i] <= piv);
		do {--j;} while (a [j] >= piv);
		if (i < j)
		{
			aux=a [i];
			a [i]=a [j];
			a [j]=aux;
		}
		else
			return j;
	} while (1);
}

int rez (int st, int dr)
{
	if (st < dr)
	{
		int x=partitionare (st, dr);
		if (x == k) return a [x];
		if (x > k) rez (st, x);
		else rez (x+1, dr);	
	}

}

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