Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Last active January 15, 2021 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/ccaed0cb17603bc9c48848859175a344 to your computer and use it in GitHub Desktop.
Save zhongyangxun/ccaed0cb17603bc9c48848859175a344 to your computer and use it in GitHub Desktop.
Heap sort algorithm based on JavaScript.
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