Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:52
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 yavgel85/d0eaeddd432d54110090a91795226c0b to your computer and use it in GitHub Desktop.
Save yavgel85/d0eaeddd432d54110090a91795226c0b to your computer and use it in GitHub Desktop.
heapsort #js #algorithm
// Sorts an array of numbers, using the heapsort algorithm.
// Use recursion.
// Use the spread operator (...) to clone the original array, arr.
// Use closures to declare a variable, l, and a function heapify.
// Use a for loop and Math.floor() in combination with heapify to create a max heap from the array.
// Use a for loop to repeatedly narrow down the considered range, using heapify and swapping values as necessary in order to sort the cloned array.
const heapsort = arr => {
const a = [...arr];
let l = a.length;
const heapify = (a, i) => {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < l && a[left] > a[max]) max = left;
if (right < l && a[right] > a[max]) max = right;
if (max !== i) {
[a[max], a[i]] = [a[i], a[max]];
heapify(a, max);
}
};
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
for (i = a.length - 1; i > 0; i--) {
[a[0], a[i]] = [a[i], a[0]];
l--;
heapify(a, 0);
}
return a;
};
// Examples
heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment