-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.java
More file actions
46 lines (37 loc) · 1.24 KB
/
MaxHeap.java
File metadata and controls
46 lines (37 loc) · 1.24 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
package dsa;
public class MaxHeap {
public static void heapify(int [] array){
for (int i = array.length /2 - 1; i >= 0 ; i--) {
heapify(array, i);
}
}
private static void heapify(int [] array, int index){
var largerIndex = index;
var leftIndex = (index * 2) + 1;
if(leftIndex < array.length && array[leftIndex] > array[largerIndex])
largerIndex = leftIndex;
var rightIndex = (index * 2) + 2;
if(rightIndex < array.length && array[rightIndex] > array[largerIndex])
largerIndex = rightIndex;
if(index == largerIndex) return;
swap(array, index, largerIndex);
heapify(array, largerIndex);
}
private static void swap(int [] array, int first, int second) {
var temp = array[first];
array[first] = array[second];
array[second] = temp;
}
public static int getKthLargest(int [] array, int k){
if (k < 1 || k > array.length)
throw new IllegalArgumentException();
var heap = new Heaps();
for (int i : array) {
heap.insert(i);
}
for (int i = 0; i < k -1 ; i++) {
heap.remove();
}
return heap.max();
}
}