1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
| #include "misc.h"
class QuickSort{
int partition(vector<int>& vec, int l, int h){
int pivot = vec[h];
int i = l-1;
for(int j=l; j<h; ++j){
if(vec[j]<=pivot){
swap(vec[++i], vec[j]);
}
}
swap(vec[++i], vec[h]);
return i;
}
public:
void sort(vector<int> &vec, int l, int h){
if(l>=h) return;
int p = partition(vec, l, h);
sort(vec, l, p-1);
sort(vec, p+1, h);
}
//K is zero based
int select(vector<int> &vec, int l, int h, int K){
if(l>h) return -1;
int p = partition(vec, l, h);
if(p==K) return vec[p];
if(p<K) return select(vec, p+1, h, K);
else return select(vec, l, p-1, K);
}
};
int main(int argc, char** argv){
vector<int> vec{5,8,3,5,8,9,6,5,2,4,6,7,9};
QuickSort qs;
int K;
if(argc < 2){
cout<<"input K"<<endl;
cin>>K;
}else{
K = stoi(argv[1]);
}
cout<<"select "<<K<<"th value is "<<qs.select(vec, 0, vec.size()-1, K)<<endl;
qs.sort(vec, 0, vec.size()-1);
for(auto x:vec) cout<<x<<" ";
cout<<endl;
return 0;
}
|
No comments:
Post a Comment