From 3d6dc4bf400c5ec856888c206d49279bfd666108 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Mon, 28 Dec 2020 22:48:09 +0200 Subject: [PATCH] Add heapsort --- snippets/heapsort.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 snippets/heapsort.md diff --git a/snippets/heapsort.md b/snippets/heapsort.md new file mode 100644 index 000000000..16c87592e --- /dev/null +++ b/snippets/heapsort.md @@ -0,0 +1,43 @@ +--- +title: heapsort +tags: algorithm,array,recursion,advanced +--- + +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. + +```js +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; +}; +``` + +```js +heapsort([6, 3, 4, 1]); // [1, 3, 4, 6] +```