-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickselect.cpp
More file actions
49 lines (48 loc) · 886 Bytes
/
quickselect.cpp
File metadata and controls
49 lines (48 loc) · 886 Bytes
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<iostream>
using namespace std;
#include<vector>
int partition(vector<int> &arr,int f,int l,int k){
int pivot=arr[l];
int i=f-1;
int j=f;
while(j<l){
if(arr[j]<pivot){
i++;
swap(arr[i],arr[j]);
}
j++;
}
swap(arr[i+1],arr[l]);
return i+1;
}
int quickselect(vector<int> &arr,int f,int l,int k){
if(f>=k){
return -1;
}
else{
int pi=partition(arr,f,l,k);
if(pi==k){
return pi;
}
else if(pi<k){
return quickselect(arr,pi+1,l,k);
}
else{
return quickselect(arr,f,pi-1,k);
}
}
}
int kthlargest(vector<int> &arr,int k){
int f=0;
int l=arr.size()-1;
quickselect(arr,f,l,k);
}
int main(){
vector<int> arr={3,7,8,3,4,1,9,0};//0 1 3 3 4 7 8 9
int k=2;
int ans=kthlargest(arr,arr.size()-k);
for(int i=0;i<arr.size();i++){
cout<<arr[i]<<" ";
}
cout<<arr[ans]<<endl;
}