@@ -28,63 +28,63 @@ export function pop(heap: Heap): Node | null {
28
28
return null ;
29
29
}
30
30
const first = heap [ 0 ] ;
31
-
32
31
const last = heap . pop ( ) ;
33
-
34
32
if ( last !== first ) {
35
33
heap [ 0 ] = last ;
36
34
siftDown ( heap , last , 0 ) ;
37
35
}
38
-
39
36
return first ;
40
37
}
41
38
42
39
function siftUp ( heap , node , i ) {
43
40
let index = i ;
44
-
45
41
while ( index > 0 ) {
46
42
const parentIndex = ( index - 1 ) >>> 1 ;
47
43
const parent = heap [ parentIndex ] ;
48
-
49
- if ( compare ( parent , node ) < 0 ) {
50
- break ;
44
+ if ( compare ( parent , node ) > 0 ) {
45
+ // The parent is larger. Swap positions.
46
+ heap [ parentIndex ] = node ;
47
+ heap [ index ] = parent ;
48
+ index = parentIndex ;
49
+ } else {
50
+ // The parent is smaller. Exit.
51
+ return ;
51
52
}
52
- swap ( heap , parentIndex , index ) ;
53
- index = parentIndex ;
54
53
}
55
54
}
56
55
57
56
function siftDown ( heap , node , i ) {
58
57
let index = i ;
59
- const halfLength = heap . length >>> 1 ;
60
-
58
+ const length = heap . length ;
59
+ const halfLength = length >>> 1 ;
61
60
while ( index < halfLength ) {
62
- let bestIndex = index * 2 + 1 ;
63
- const rightIndex = index * 2 + 2 ;
64
-
65
- // If the right node is smaller, swap with the smaller of those.
66
- if (
67
- heap . length > rightIndex &&
68
- compare ( heap [ rightIndex ] , heap [ bestIndex ] ) < 0
69
- ) {
70
- bestIndex = rightIndex ;
71
- }
72
-
73
- if ( compare ( node , heap [ bestIndex ] ) < 0 ) {
74
- break ;
61
+ const leftIndex = ( index + 1 ) * 2 - 1 ;
62
+ const left = heap [ leftIndex ] ;
63
+ const rightIndex = leftIndex + 1 ;
64
+ const right = heap [ rightIndex ] ;
65
+
66
+ // If the left or right node is smaller, swap with the smaller of those.
67
+ if ( compare ( left , node ) < 0 ) {
68
+ if ( rightIndex < length && compare ( right , left ) < 0 ) {
69
+ heap [ index ] = right ;
70
+ heap [ rightIndex ] = node ;
71
+ index = rightIndex ;
72
+ } else {
73
+ heap [ index ] = left ;
74
+ heap [ leftIndex ] = node ;
75
+ index = leftIndex ;
76
+ }
77
+ } else if ( rightIndex < length && compare ( right , node ) < 0 ) {
78
+ heap [ index ] = right ;
79
+ heap [ rightIndex ] = node ;
80
+ index = rightIndex ;
81
+ } else {
82
+ // Neither child is smaller. Exit.
83
+ return ;
75
84
}
76
-
77
- swap ( heap , bestIndex , index ) ;
78
- index = bestIndex ;
79
85
}
80
86
}
81
87
82
- function swap ( heap , left , right ) {
83
- const item = heap [ left ] ;
84
- heap [ left ] = heap [ right ] ;
85
- heap [ right ] = item ;
86
- }
87
-
88
88
function compare ( a , b ) {
89
89
// Compare sort index first, then task id.
90
90
const diff = a . sortIndex - b . sortIndex ;
0 commit comments