Heapsort Build And Extract Max (JavaScript)

Sort an array by building a max heap in place then repeatedly extracting the maximum element to the end of the array.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
function heapsort(arr) {
  const n = arr.length;
  function siftDown(start, end) {
    let root = start;
    while (root * 2 + 1 <= end) {
      let child = root * 2 + 1;
      if (child + 1 <= end && arr[child] < arr[child + 1]) child++;
      if (arr[root] < arr[child]) { [arr[root], arr[child]] = [arr[child], arr[root]]; root = child; }
      else return;
    }
  }
  for (let i = (n - 2) >>> 1; i >= 0; i--) siftDown(i, n - 1);
  for (let end = n - 1; end > 0; end--) {
    [arr[0], arr[end]] = [arr[end], arr[0]];
    siftDown(0, end - 1);
  }
  return arr;
}

How it works

Count the functions i, heapsort and siftDown as the entire surface area of Heapsort Build And Extract Max (JavaScript).

The structure is a loop within a loop: while (root * 2 + 1 <= end) outside, for (let i = (n - 2) >>> 1; i >= 0; i--) siftDown(i, n - 1); inside.

Using it

The main signature reads let i = (n - 2)

Key statements

if (arr[root] < arr[child]) { [arr[root], arr[child]] = [arr[child], arr[root]]; root = child; }
if (child + 1 <= end && arr[child] < arr[child + 1]) child++;
for (let i = (n - 2) >>> 1; i >= 0; i--) siftDown(i, n - 1);

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `i`, `heapsort`, `siftDown` at load time.