-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickselect.java
More file actions
69 lines (41 loc) · 1.26 KB
/
Quickselect.java
File metadata and controls
69 lines (41 loc) · 1.26 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.*;
public class Quickselect{
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={1,8,7,3,2,5,4,-1,83};
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
int k=4;
int r=quickselect(arr,k,0,arr.length-1);
System.out.println("Kth largest is"+r);
}
static int quickselect(int arr[],int k,int st, int end) {
int pi=partition(arr,st,end);
if(pi==k-1) {
return arr[pi];
}
else if(pi<k-1) {
return quickselect(arr,k,pi+1,end);
}
else {
return quickselect(arr, k, st,pi-1);
}
}
static int partition(int arr[],int st, int en){
int partind=st;
int j=st;
while(j<en){
if(arr[j]<arr[en]){
int temp=arr[j];
arr[j]=arr[partind];
arr[partind]=temp;
partind++;
}
j++;
}
int temp =arr[en];
arr[en]=arr[partind];
arr[partind]=temp;
return partind;
}
}