Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Last active June 11, 2021 17:17
Show Gist options
  • Save CarlaTeo/3626a106f7395f7d801cdd528e9c22e2 to your computer and use it in GitHub Desktop.
Save CarlaTeo/3626a106f7395f7d801cdd528e9c22e2 to your computer and use it in GitHub Desktop.
[JS] Heap sort
function heapSort(array) {
const heap = heapify(array);
let lengthToConsider = array.length;
for(let i = array.length - 1; i > 0; i--) {
swap(array, i, 0);
lengthToConsider--;
descendHeap(array, lengthToConsider, 0);
}
}
function heapify(array) {
const nOfElements = array.length;
const halfHeapIndex = Math.floor(nOfElements / 2) - 1;
for(let i = halfHeapIndex; i <= 0; i--) {
descendHeap(array, nOfElements, i);
}
}
function descendHeap(array, arrayLength, indexToDescend) {
const leftIndex = 2 * indexToDescend + 1;
const rightIndex = 2 * indexToDescend + 2;
let maxIndex = indexToDescend;
if(leftIndex < arrayLength && array[leftIndex] > array[maxIndex]){
maxIndex = leftIndex;
}
if(rightIndex < arrayLength && array[rightIndex] > array[maxIndex]){
maxIndex = rightIndex;
}
if(maxIndex != indexToDescend) {
swap(array, indexToDescend, maxIndex);
descendHeap(array, arrayLength, maxIndex);
}
}
function swap(array, i, j) {
const aux = array[i];
array[i] = array[j];
array[j] = aux;
}
// -------------------------- Test -----------------------------------------//
const array = [51, 46, 17, 34, 41, 15, 14, 23, 30, 21, 10, 12]
heapSort(array);
console.log(array); // [10, 12, 14, 15, 17, 21, 23, 30, 34, 41, 46, 51]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment