Cod sursa(job #526516)

Utilizator Gaby_mMititelu Gabriel Gaby_m Data 28 ianuarie 2011 16:02:23
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include<cstdio>
#include<fstream>
#include<cstdlib>
using namespace std;

const int NMax = 3000000;

int a[NMax], k, n;


void swap(int i, int j){
	int aux = a[i];
	a[i] = a[j];
	a[j] = aux;
}


int partition(int left, int right){
	int poz = rand() % (right-left) + left;
	swap(left, poz);
	int el = a[left];
	int i = left;
	for (int j = left + 1; j < right; j++) {
		if (a[j] <= el){
			i++;
			swap(i,j);
		}
	}

	swap(left, i);
	return i;
}

int qSort(int left, int right, int k) {

	if (left == right) return a[left];

	int q = partition(left, right);
	int poz = q - left + 1;

	if (poz == k) return a[q];
	else if (k < poz) return qSort(left, q, k);
	else return qSort(q+1, right, k-poz);
		

}

int main() {

	ifstream f("sdo.in");

	freopen("sdo.out", "w", stdout);

	f>>n>>k;	
	for (int i = 0; i < n ; i++) {
		f>>a[i];
	}

	printf("%d\n", qSort(0, n, k));
	return 0;
}