//
// main.cpp
//findk
//
// Created by Xiao Bang on 2017/6/28.
// Copyright © 2017年 Xiao Bang. All rights reserved.
//
#include <vector>
#include <iostream>
using namespace std;
template <typename Comparable>
const Comparable & median3(vector<Comparable> & a, int left, int right){
int center = (left + right) / 2;
if(a[center] < a[left])
swap(a[center],a[left]);
if(a[right] < a[left])
swap(a[right],a[left]);
if (a[right] < a[center])
swap(a[right],a[center]);
swap(a[center],a[right - 1]);
return a[right - 1];
}
template <typename Comparable>
Comparable partion( vector<Comparable> & a, int left, int right){
const Comparable & pivot = median3(a,left,right);
int i = left;
int j = right - 1;
for (;;) {
while(a[++i] < pivot) {}
while(pivot < a[--j]) {}
if (i < j)
swap(a[i],a[j]);
else break;
}
swap (a[i],a[right - 1]);
return i;
}
template <typename Comparable>
Comparable findK(vector<Comparable> & a,int k) {
int nk =k -1;
int left = 0;
int right = (int)(a.size()-1);
int index = partion(a,left,right);
while(index != nk) {
if (nk < index)
index = partion(a,left, index -1);
else
index = partion(a,index+1,right);
}
return a[nk];
}
int main(int argc, const char * argv[]) {
vector <int> array1 {1,2,4,6,7,8,1,0,1,14,12,16,44,66,34,72,3,8,4,9,0,14};
// vector <int> array1 {1,2,4,6,7,8,1,0,1,14,12,14,12,16,44,66,34,72};
int b= findK(array1,10);
cout << b << '\t';
}