Cod sursa(job #2104671)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 12 ianuarie 2018 02:52:14
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#define NMAX 3000001

using namespace std;

int a[NMAX], n, k;

void read() {

	ifstream in("sdo.in");

	in >> n >> k;
	for (int i = 1; i <= n; i++)
		in >> a[i];
	
	in.close();
}

void quicksort(int x, int y) {

	if (x < y) {

		int i = x, j = y;
		int pos = rand() % (y - x + 1) + x;

		swap(a[i], a[pos]);

		int depX = 0, depY = -1;
		while (i < j) {

			if (a[i] > a[j]) {

				swap(a[i], a[j]);
				int aux = depX;
				depX = -depY;
				depY = -aux;
			}
			i += depX;
			j += depY;
		}

		if (k < i)
			quicksort(x, i - 1);
		if (i < k)
			quicksort(i + 1, y);
	}
}

int main() {

	srand(static_cast<unsigned int>(time(NULL)));
	read();
	quicksort(1, n);

	ofstream out("sdo.out");
	out << a[k] << "\n";
	out.close();
}