| 57 | } |
| 58 | |
| 59 | function siftDown<T: Node>(heap: Heap<T>, node: T, i: number): void { |
| 60 | let index = i; |
| 61 | const length = heap.length; |
| 62 | const halfLength = length >>> 1; |
| 63 | while (index < halfLength) { |
| 64 | const leftIndex = (index + 1) * 2 - 1; |
| 65 | const left = heap[leftIndex]; |
| 66 | const rightIndex = leftIndex + 1; |
| 67 | const right = heap[rightIndex]; |
| 68 | |
| 69 | // If the left or right node is smaller, swap with the smaller of those. |
| 70 | if (compare(left, node) < 0) { |
| 71 | if (rightIndex < length && compare(right, left) < 0) { |
| 72 | heap[index] = right; |
| 73 | heap[rightIndex] = node; |
| 74 | index = rightIndex; |
| 75 | } else { |
| 76 | heap[index] = left; |
| 77 | heap[leftIndex] = node; |
| 78 | index = leftIndex; |
| 79 | } |
| 80 | } else if (rightIndex < length && compare(right, node) < 0) { |
| 81 | heap[index] = right; |
| 82 | heap[rightIndex] = node; |
| 83 | index = rightIndex; |
| 84 | } else { |
| 85 | // Neither child is smaller. Exit. |
| 86 | return; |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | function compare(a: Node, b: Node) { |
| 92 | // Compare sort index first, then task id. |