Cod sursa(job #1255020)

Utilizator fhandreiAndrei Hareza fhandrei Data 4 noiembrie 2014 00:09:43
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
// FMI - Grupa 135 - Semigrupa 2 - Hareza Andrei
// Include
#include <fstream>
#include <stdlib>
using namespace std;

// Constante
const int sz = 3000001;

// Functii
int findPosElement(int *values, int left, int right, int pos);

// Variabile
ifstream in("sdo.in");
ofstream out("sdo.out");

int num, pos;
int values[sz];

// Main
int main()
{
	srand(3110);
	in >> num >> pos;
	for(int i=1 ; i<=num ; ++i)
		in >> values[i];
	
	out << findPosElement(values, 1, num, pos) << '\n';
	
	in.close();
	out.close();
	return 0;
}

int findPosElement(int *values, int left, int right, int pos)
{
	int currentLeft = left;
	int currentRight = right;
	int point = rand()%(right-left+1) + left;
	
	while(currentLeft <= currentRight)
	{
		while(values[currentLeft] < values[point])
			++currentLeft;
		while(values[point] < values[currentRight])
			--currentRight;
		
		if(currentLeft <= currentRight)
		{
			if(currentLeft == point)
				point = currentRight;
			else if(currentRight == point)
				point = currentLeft;
			swap(values[currentLeft++], values[currentRight--]);
		}
	}
	
	if(point == pos)
		return values[point];
	if(point < pos)
		return findPosElement(values, point+1, right, pos);
	else
		return findPosElement(values, left, point-1, pos);
}