Created
August 17, 2021 04:15
-
-
Save PradipShrestha/48cea3ce20edfbf9c80272acec37c214 to your computer and use it in GitHub Desktop.
Heapify javascript
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
class Heap { | |
buildHeaps(nums) { | |
for (let i = Math.ceil(nums.length / 2) - 1; i >= 0; i--) { | |
this.heapify(nums, i) | |
} | |
} | |
heapify(nums, i) { | |
let l = i * 2 + 1 | |
let r = l + 1 | |
let max = i | |
if (r <= nums.length) { | |
max = nums[l] > nums[r] ? l : r | |
} else if (l <= nums.length && nums[l] > nums[i]) { | |
max = l | |
} | |
if (max !== i) { | |
this.swap(nums, max, i) | |
this.heapify(nums, max) | |
} | |
} | |
swap(nums, max, i) { | |
if (nums[max] > nums[i]) { | |
let temp = nums[i] | |
nums[i] = nums[max] | |
nums[max] = temp | |
} | |
} | |
} | |
let h = new Heap() | |
let nums = [2, 5, 3, 60, 11, 20, 1, 45, 7] | |
h.buildHeaps(nums) | |
console.log(nums) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment