Cod sursa(job #771206)

Utilizator mi5humihai draghici mi5hu Data 25 iulie 2012 10:52:39
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <stdio.h>
#include <cstdlib>
#define NMAX 3000001

using namespace std;

int v[NMAX], n, K;

void sw(int* a, int* b) {
     int aux = *a; 
     *a = *b;
     *b = aux;     
}

int pivot(int a, int b) {
    return a + (rand() % (b - a));
}

void qSort_(int a, int b) {
    if (a >= b) { 
        return;   
    }
    
    int p = pivot(a, b);
    int piv = v[p];
    sw(&v[p], &v[b]);
    int left = a - 1;
    int right = b;
        
    while (left < right) {
        while (left < right && piv > v[++left]) {}
        while (left < right && piv < v[--right]) {}
        sw(&v[left], &v[right]);
    }
    
    sw(&v[b], &v[left]);
    
    if (left < K - 1) {
        qSort_(left + 1, b);      
    } else if (left > K - 1) {
        qSort_(a, left - 1);       
    }
      
}

void read_() {
    scanf("%d%d", &n, &K);
    for (int i = 0; i < n; i++) {
        scanf("%d", &v[i]);
    }     
}

void print_() {
    printf("%d", v[K - 1]);
} 

int main() {
    freopen("sto.in", "r", stdin);
    freopen("sto.out", "w", stdout);
    
    read_();
    qSort_(0, n - 1);
    print_();
    
    return 0;
}