Skip to content

Commit 5cc29d8

Browse files
committed
heapify
1 parent 298bb38 commit 5cc29d8

File tree

2 files changed

+18
-18
lines changed

2 files changed

+18
-18
lines changed

src/main/java/grey/algorithm/code11_heap/Code_0001_LintCode_0130_Heapify.java

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,27 +8,26 @@
88
//右孩子 2 * i + 2
99
//父节点 (i - 1)/ 2
1010
public class Code_0001_LintCode_0130_Heapify {
11-
public void heapify(int[] a) {
12-
for (int index = a.length - 1; index >= 0; index--) {
13-
int i = index;
14-
int leftChildIndex = 2 * i + 1;
15-
while (leftChildIndex < a.length) {
16-
int minIndex = leftChildIndex + 1 < a.length && a[leftChildIndex] > a[leftChildIndex + 1] ? leftChildIndex + 1 : leftChildIndex;
17-
minIndex = a[i] < a[minIndex] ? i : minIndex;
18-
if (minIndex == i) {
11+
12+
public void heapify(int[] arr) {
13+
for (int i = arr.length - 1; i >= 0; i--) {
14+
int index = i;
15+
int left = 2 * index + 1;
16+
while (left < arr.length) {
17+
int best = left + 1 < arr.length && arr[left + 1] < arr[left] ? left + 1 : left;
18+
if (arr[best] >= arr[index]) {
1919
break;
2020
}
21-
swap(a, i, minIndex);
22-
i = minIndex;
23-
leftChildIndex = 2 * i + 1;
21+
swap(arr, best, index);
22+
index = best;
23+
left = 2 * index + 1;
2424
}
2525
}
2626
}
27-
public void swap(int[] arr, int i, int j) {
28-
if (i != j && arr != null && arr.length > 1) {
29-
arr[i] = arr[i] ^ arr[j];
30-
arr[j] = arr[i] ^ arr[j];
31-
arr[i] = arr[i] ^ arr[j];
32-
}
27+
28+
public static void swap(int[] arr, int i, int j) {
29+
int t = arr[i];
30+
arr[i] = arr[j];
31+
arr[j] = t;
3332
}
3433
}

src/main/java/grey/algorithm/code11_heap/Code_0002_MaxHeap.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
// 大根堆:完全二叉树中,每棵树的最大值都是头节点的值
2525
// heapify和heapInsert都是logN级别的复杂度,因为N个节点的二叉树高度是logN
2626
public class Code_0002_MaxHeap {
27+
2728
private final int[] heap;
2829
private int heapSize;
2930

@@ -63,7 +64,7 @@ private void heapify() {
6364
int largest // bigger index
6465
= left + 1 < heapSize // right child exist
6566
&& heap[left + 1] > heap[left] // compare left child and right child
66-
? left + 1 : left;
67+
? left + 1 : left;
6768
largest = heap[largest] > heap[index] ? largest : index;
6869
if (largest == index) {
6970
break;

0 commit comments

Comments
 (0)