Skip to content

Instantly share code, notes, and snippets.

@jharris-code
Last active January 22, 2019 20:54
Show Gist options
  • Save jharris-code/f7f54f76300e44aab92f5b62bbfcdab7 to your computer and use it in GitHub Desktop.
Save jharris-code/f7f54f76300e44aab92f5b62bbfcdab7 to your computer and use it in GitHub Desktop.
Heap Sort
//Create a sorted array (ascending) from a max heap
//Time Complexity: O(N log N)
//Space Complexity: O(1) because array is sorted in place
const heapSort = (arr, end) => {
while(end > 0){
let tmp = arr[end];
arr[end] = arr[0];
arr[0] = tmp;
end -= 1;
//siftDown is implemented in Building Heaps section below
arr = siftDown(arr, 0, end)
}
return arr;
}
console.log(heapSort(arr, arr.length - 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment