Cod sursa(job #1994389)

Utilizator clau_rClaudia clau_r Data 24 iunie 2017 20:34:33
Problema Statistici de ordine Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<time.h>
#include <stdlib.h>

using namespace std;

void swap(int& a, int& b) {
    int tmp = a;
    a = b;
    b = tmp;
}

int get_index(vector<int>&a, int start, int end, int index) {
    std::cout << "Start: "<< start << ":" << end << "\n";

   for (int i= start; i<= end; i++) {
       std::cout << "at index " << i << " " << a[i] << "\n";
       if ( i < index && a[i] > a[index] ) {
           std::swap(a[index], a[index+1]);
           std::swap(a[index], a[i]);
           index = index + 1;
       }
       if ( (i < index && a[i] > a[index])||(i > index && a[i] < a[index]) ) {
            std::cout << "Swap " << a[i] << " " << a[index] << " " << i << "-" << index << "\n";
            std::swap(a[i], a[index]);
            std::cout << a[i] << " " << a[index] << "\n";
            index = i;
        }
       
    }
    return index;    
}

int nth_element(std::vector<int>& a, int start, int end, int k) {
    std::srand(std::time(0));
    int index = start + (std::rand() % (end - start + 1));
    std::cout << "Initial index = " << index << " " << a[index] << "=>";
    index = get_index(a, start, end, index);
    std::cout << "Index = " << index << "\n";
    
    if (k == index) {
        return a[index];   
    } else if (k < index) {
        index = nth_element(a, start, index -1, k);    
    } else {
        index = nth_element(a, index + 1, end, k);    
    }

    return std::max(-1, index);
}

int main(){
    ifstream fin;
    fin.open("sdo.in");
    int n, k;
    fin >> n >> k;
    std::vector<int> a;
    a.reserve(n);

    for (int i = 0; i< n;i++) {
        fin >> a[i];
        std::cout << a[i] << "\n";
    }
    
    ofstream fout;
    fout.open("sdo.out");
    fout << nth_element(a, 0, n-1, k-1) << "\n";
   
}