-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSelect.java
More file actions
35 lines (29 loc) · 798 Bytes
/
QuickSelect.java
File metadata and controls
35 lines (29 loc) · 798 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
public class QuickSelect {
public static int select(int a[],int k){
int left = 0,right = a.length -1;
while(left < right){
int q = partition(a,left,right);
if(k == q){
return a[q];
}else if(k>q){
left = q+1;
}else{right = q-1;}
}
return 0;
}
public static int partition(int[] a, int left,int right){
int piv = right;
for(int i = piv -1; i>=0; i--){
if(a[i]>a[piv]){
int temp = a[piv-1];
a[piv-1] = a[i];
a[i] = temp;
temp = a[piv];
a[piv] = a[piv-1];
a[piv-1] = temp;
piv--;
}
}
return piv;
}
}