Last active
January 22, 2019 20:54
-
-
Save jharris-code/f7f54f76300e44aab92f5b62bbfcdab7 to your computer and use it in GitHub Desktop.
Heap Sort
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
| //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