-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.java
More file actions
49 lines (42 loc) · 1.12 KB
/
MaxHeap.java
File metadata and controls
49 lines (42 loc) · 1.12 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
package Sorting;
public class MaxHeap {
public int[] array;
public int arraySize = 0;
public int heapSize = 0;
public MaxHeap(int[] A) {
int n = A.length;
array = A;
arraySize = heapSize = n;
}
public void buildMaxHeap() {
for (int i = heapSize / 2 - 1; i >= 0; i--) {
maxHeapify(i);
}
}
public int getParentIndex(int i) {
return (i - 1) / 2;
}
public int getLeftChildIndex(int i) {
return 2 * i + 1;
}
public int getRightChildIndex(int i) {
return 2 * i + 2;
}
public void maxHeapify(int i) {
int left = getLeftChildIndex(i);
int right = getRightChildIndex(i);
int largest = i;
if (left < heapSize && array[i] < array[left]) {
largest = left;
}
if (right < heapSize && array[largest] < array[right]) {
largest = right;
}
if (largest != i) {
int temp = array[largest];
array[largest] = array[i];
array[i] = temp;
maxHeapify(largest);
}
}
}