-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.java
49 lines (38 loc) · 1.06 KB
/
Heap.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
package com.mckinsey.engage.risk.services.warning;
public class Heap {
public void main(String[] args) {
int[] array = new int[];
int n = array.length;
for (int i = (n / 2) - 1; i >= 0; i--) {
maxHeapify(array, i);
}
}
/*
6
5 3
4 2 1
*/
void maxHeapify(int array[], int index) {
int lc = 2 * index + 1;
int rc = 2 * index + 2;
if (lc >= array.length || rc > array.length)
return;
boolean isLcGreater = false;
boolean isRcGreater = false;
if (array[index] < array[lc]) {
int temp = array[index];
array[index] = array[lc];
array[lc] = temp;
isLcGreater = true;
} else if (array[index] < array[rc]) {
int temp = array[index];
array[index] = array[rc];
array[rc] = temp;
isRcGreater = true;
}
if (isLcGreater)
maxHeapify(array, lc);
if (isRcGreater)
maxHeapify(array, rc);
}
}