forked from GDSC-IGDTUW-Autumn-of-Code-2022/dsa-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KthLargestElementInAnArray.java
59 lines (51 loc) · 1.45 KB
/
KthLargestElementInAnArray.java
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
import java.util.*;
public class KthLargestElementInAnArray {
public static void main(String[] args){
int[] nums1 = {3,2,1,5,6,4};
int k1 = 2;
System.out.println(Arrays.toString(nums1) + "," + k1 + " -> " + findKthLargest(nums1, k1));
//Answer is 5
int[] nums2 = {1,2,7,5,6,9};
int k2 = 1;
System.out.println(Arrays.toString(nums2) + "," + k2 + " -> " + findKthLargest(nums2, k2));
//Answer is 9
}
public static int findKthLargest(int[] nums, int k) {
k = nums.length - k;
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
final int j = partition(nums, lo, hi);
if(j < k) {
lo = j + 1;
} else if (j > k) {
hi = j - 1;
} else {
break;
}
}
return nums[k];
}
private static int partition(int[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
while(true) {
while(i < hi && less(a[++i], a[lo]));
while(j > lo && less(a[lo], a[--j]));
if(i >= j) {
break;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
private static void exch(int[] a, int i, int j) {
final int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
private static boolean less(int v, int w) {
return v < w;
}
}