Last active
October 16, 2018 07:40
-
-
Save sharmaabhinav/53ed8aada5fc486a1991be5cbbd71117 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//var arr = [7, 5, 1, 4, 2, 3,8] | |
function createHeap (arr) { | |
var startIndex = Math.floor(arr.length / 2) - 1 | |
while(startIndex >= 0) { | |
heapify(arr, startIndex) | |
startIndex -= 1 | |
} | |
return arr | |
} | |
function heapify (arr, startIndex) { | |
var leftChild = arr[2 * startIndex + 1] | |
var rightChild = arr[2 * startIndex + 2] | |
var temp = arr[startIndex] | |
// leaf node | |
if (!leftChild && !rightChild) { | |
return | |
} | |
// right most node on n-1 level | |
if (!rightChild) { | |
if (leftChild < temp) { | |
arr[startIndex] = leftChild | |
arr[2 * startIndex + 1] = temp | |
} | |
return | |
} | |
if (arr[startIndex] < leftChild && arr[startIndex] < rightChild) { | |
return | |
} | |
var temp = arr[startIndex] | |
if (leftChild < rightChild) { | |
arr[startIndex] = leftChild | |
arr[2 * startIndex + 1] = temp | |
heapify(arr, 2 * startIndex + 1) | |
} else { | |
arr[startIndex] = rightChild | |
arr[2 * startIndex + 2] = temp | |
heapify(arr, 2 * startIndex + 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment