Cod sursa(job #1843967)

Utilizator stefanmereutaStefan Mereuta stefanmereuta Data 9 ianuarie 2017 16:43:07
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <time.h>
#include <algorithm>
#include <vector>

using namespace std;
/*
void afis(vector<int> &v) {
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << "\n";
}*/

void quicksort(vector<int> &v, int k, int st, int dr) {
    //printf("quick de %d %d\n", st, dr);
    int pivot = v[rand() % (dr - st) + st];
    //printf("pivot=%d\n", pivot);
    int i = st, j = dr, aux;

    do {
        while (v[i] < pivot && i < dr) {
            i++;
        }

        while (v[j] > pivot && j > st) {
            j--;
        }

        if (i <= j) {
            aux = v[i];
            v[i] = v[j];
            v[j] = aux;

            i++;
            j--;
        }
    } while (i <= j);

    //afis(v);

    //printf("i=%d j=%d\n", i, j);

    if (st < j && k <= j) {
        //printf("v[k]=%d<=pivot=%d\n", v[k], pivot);
        quicksort(v, k, st, j);
    } else if (i < dr && k >= i) {
        //printf("v[k]=%d>=pivot=%d\n", v[k], pivot);
        quicksort(v, k, i, dr);
    } else {
        //printf("v[k]=%d e pivot=%d\n", v[k], pivot);
    }
}

int main()
{
    ifstream fin("sdo.in");
    ofstream fout("sdo.out");

    srand(clock());

    int n, k, x;
    vector<int> v;

    fin >> n >> k;

    k--;

    for (int i = 0; i < n; i++) {
        fin >> x;
        v.push_back(x);
    }

    quicksort(v, k, 0, n - 1);

    fout << v[k];

    fin.close();
    fout.close();

    return 0;
}