Created
April 13, 2023 02:24
-
-
Save cindywu/678abdf21ed6ab7f2f5e189b441f9bad to your computer and use it in GitHub Desktop.
minHeapify an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stones = [2,7,4,1,8,1] | |
function minHeapify(arr: number[]): number[]{ | |
// push 0-th position to the end | |
arr.push(arr[0]) // [2, 7, 4, 1, 8, 1, 2] | |
// we will ignore arr[0] for math purposes | |
let heap = arr | |
let cur = Math.floor(heap.length - 1)/2 // (7-1)/2 = 6/2 = 3 | |
/* | |
7(1) | |
/ \ | |
4(2) 1(3)<-- | |
/ \ / \ | |
8(4) 1(5) 2(6) | |
*/ | |
while (cur > 0) { | |
let i = cur // 3 | |
while (2 * i < heap.length) { // left child exists | |
if (2 * i + 1 < heap.length && // right child exists | |
heap[2 * i + 1] < heap[2 * i] && // right < left | |
heap[i] > heap[2 * i + 1]) { // current > right | |
// swap current with right child | |
let tmp = heap[i] | |
heap[i] = heap[2 * i + 1] | |
heap[2 * i + 1] = tmp | |
i = 2 * i + 1 | |
} else if (heap[i] > heap[2 * i]) { | |
// swap left child | |
let tmp = heap[i] | |
heap[i] = heap[2 * i] | |
heap[2 * i] = tmp | |
i = 2 * i | |
} else { | |
break; | |
} | |
} | |
cur = cur - 1; | |
} | |
return heap | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment