Last active
January 15, 2021 07:33
-
-
Save zhongyangxun/ccaed0cb17603bc9c48848859175a344 to your computer and use it in GitHub Desktop.
Heap sort algorithm based on 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
function heapSort(arr) { | |
for (let i = (arr.length >> 1) - 1; i >= 0; i--) { | |
adjust(arr, i, arr.length); | |
} | |
for (let j = arr.length - 1; j >= 0; j--) { | |
swap(arr, 0, j); | |
adjust(arr, 0, j); | |
} | |
return arr; | |
} | |
function adjust(arr, index, length) { | |
let currIndex = index; | |
for (let i = (index << 1) + 1; i < length; i++) { | |
if (i + 1 < length && arr[i + 1] > arr[i]) { | |
i++; | |
} | |
if (arr[i] > arr[currIndex]) { | |
swap(arr, i, currIndex); | |
currIndex = i; | |
} else { | |
break; | |
} | |
} | |
} | |
function swap(arr, a, b) { | |
const temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment