Skip to content

Instantly share code, notes, and snippets.

@cindywu
Created April 13, 2023 02:24
Show Gist options
  • Save cindywu/742056c5a33fc36e62de549450b790e3 to your computer and use it in GitHub Desktop.
Save cindywu/742056c5a33fc36e62de549450b790e3 to your computer and use it in GitHub Desktop.
maxHeapify an array
function maxHeapify(arr: any): any {
arr.push(arr[0]) // push 0th position to end
let heap = arr
let cur = Math.floor(heap.length - 1)/2
while (cur > 0) { // ignore the 0th index bc we pushed that value to the end
// go from the half way mark down to 1
let i = cur // start a the half way and work back up to 1
// while left child position is less than length of heap
while (2 * i < heap.length) { // while cur has a left child
if (2 * i + 1 < heap.length && // if cur has a right child too
heap[2 * i + 1] < heap[2 * i] && // if right child < left child
heap[i] < heap[2 * i + 1]) { // cur < right
// swap cur 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]) { // only has left child
// cur < left
// swap cur with 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