Cod sursa(job #539242)

Utilizator c_adryanChitescu Adrian c_adryan Data 22 februarie 2011 18:42:19
Problema Statistici de ordine Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <cassert>
using namespace std;


int partition ( vector<int> &v ,int low , int high ){
	int piv = (low+high)/2;//rand()% high + low;
	swap(v[high], v[piv]); 
	piv = high;
	int i = low -1  , j = high ;
	while( 1 ) {
		while( v[ ++i] < v[piv] ) if( i == high ) break;
		while( v[ --j] > v[piv] ) if( j == low  ) break;
		if( i >= j ) break;
		swap(v[i],v[j]);

	}
	swap (v[high],v[i] );
	return i;

	
}

int kth_min( vector<int> &v , int low , int high , int k ) {
	int pos = partition( v , low,  high);
	if( pos+1  == k ) return v[ pos  ] ;
	else if( k <= pos ) 
			return kth_min(v,low , pos -1   ,k);
		else
			return kth_min(v,pos+1, high ,k);

}


int main(){
	vector<int> v;
	ifstream in("sdo.in");
	int n ,k;
	
	in>> n >> k;
	v.resize(n);

	for( int i = 0 ; i < n ; i++)
			in>> v[i];
	
	ofstream out("sdo.out");
	out<< kth_min(v,0,n-1,k);
	
	return 0;
}