File tree Expand file tree Collapse file tree 2 files changed +18
-18
lines changed
src/main/java/grey/algorithm/code11_heap Expand file tree Collapse file tree 2 files changed +18
-18
lines changed Original file line number Diff line number Diff line change 8
8
//右孩子 2 * i + 2
9
9
//父节点 (i - 1)/ 2
10
10
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 ] ) {
19
19
break ;
20
20
}
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 ;
24
24
}
25
25
}
26
26
}
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 ;
33
32
}
34
33
}
Original file line number Diff line number Diff line change 24
24
// 大根堆:完全二叉树中,每棵树的最大值都是头节点的值
25
25
// heapify和heapInsert都是logN级别的复杂度,因为N个节点的二叉树高度是logN
26
26
public class Code_0002_MaxHeap {
27
+
27
28
private final int [] heap ;
28
29
private int heapSize ;
29
30
@@ -63,7 +64,7 @@ private void heapify() {
63
64
int largest // bigger index
64
65
= left + 1 < heapSize // right child exist
65
66
&& heap [left + 1 ] > heap [left ] // compare left child and right child
66
- ? left + 1 : left ;
67
+ ? left + 1 : left ;
67
68
largest = heap [largest ] > heap [index ] ? largest : index ;
68
69
if (largest == index ) {
69
70
break ;
You can’t perform that action at this time.
0 commit comments