Cod sursa(job #1548911)

Utilizator FayedStratulat Alexandru Fayed Data 11 decembrie 2015 17:00:06
Problema Statistici de ordine Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 2.41 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

int *V;
int *Vcpy;
int len, demandedIndex;

void swap(int *x, int *y) {

	int aux = *x;
	*x = *y;
	*y = aux;
}

// void sortArray(int *a, int left, int right) {

// 	int switched = 0;
	
// 	do {

// 		switched = 0;

// 		for(int i = left; i < right - 1; ++i) {
// 			if(a[i] > a[i + 1]) {
// 				swap(&a[i], &a[i + 1]);
// 				switched = 1;
// 			}
// 		}

// 	} while(switched);
// }

// int getMedian(int *a, int left, int right) {

// 	sortArray(a, left, right);
// 	int med = (right - left + 1) / 2;
	
// 	return a[med];
// }

int partition(int left, int right) {

	int index = (left + right) / 2;
	int pivot = V[index];
	left--;
	right;
	while(1) {
		
		left++;
		while(V[left] < pivot)
			left++;

		right--;
		while(V[right] > pivot)
			right--;

		if(left < right)
			swap(&V[left], &V[right]);
		else return right;
	}

	return 0;
}

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

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

	int index = partition(left, right);
	int smaller = index - left;

	if(k == smaller) {
		return V[index];
	} else if(k < smaller) {
		return randomSelect(left, index, k);
	} else if(k > smaller) {
		return randomSelect(index + 1, right, k);
	}
}

// int getBestIndex(int *a, int size) {

// 	int medians[200001];
// 	int bestIndex;
// 	int k = 0;

// 	for(int i = 0; i + 5 < size; i += 5) {
// 		medians[k++] = getMedian(a, i, i + 5);
// 	}

// 	srand(time(NULL));

// 	int randPivot = rand() % size;
// 	bestIndex = randomSelect(medians, 0, k, (k + 1) / 2, randPivot);

// 	return bestIndex;
// }

// int getUpperBoundIndex(int *a, int left, int right, int k) {

// 	int upperBoundIndex = getBestIndex(a, right - left);
// 	int bestIndex = randomSelect(a, left, right, k, upperBoundIndex);

// 	return bestIndex;
// }

int main(int argc, char **argv) {

	// char filename[20];
	// strcpy(filename, argv[2]);

	// FILE *input = fopen(filename, "r");

	// int len = atoi(argv[1]);
	freopen("sdo.in", "r", stdin);
	freopen("sdo.out", "w", stdout);

	scanf("%d %d", &len, &demandedIndex);

	V = malloc((len) * sizeof(int));
	//Vcpy = malloc((len) * sizeof(int));
	
	for(int i = 0; i < len; ++i) {
		scanf("%d", &V[i]);
	}

	//int demandedIndex = (int)floor(((double)len / 10) * 9);
	//int bestIndex = getUpperBoundIndex(Vcpy, 0, len, demandedIndex);
	printf("%d", randomSelect(0, len, demandedIndex));

	//printf("%d\n", V[bestIndex]);

	return 0;
}