-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathheapify.java
More file actions
39 lines (35 loc) · 871 Bytes
/
heapify.java
File metadata and controls
39 lines (35 loc) · 871 Bytes
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
public class Solution {
/**
* @param A: Given an integer array
* @return: void
*/
public void heapify(int[] A) {
// write your code here
for (int i = 1; i < A.length; i++) {
minHeapify(A, i);
}
}
public void minHeapify(int[] A, int index) {
if (hasParent(index)) {
int p = getParent(index);
if (A[index] < A[p]) {
swap(A, p, index);
minHeapify(A, p);
}
}
}
public boolean hasParent(int index) {
if ((index - 1) / 2 >= 0) {
return true;
}
return false;
}
public int getParent(int index) {
return (index - 1) / 2;
}
public void swap(int[] A, int a, int b) {
int temp = A[a];
A[a] = A[b];
A[b] = temp;
}
}