Skip to content

Commit 8ac2d11

Browse files
committed
Create index.js
1 parent 6395338 commit 8ac2d11

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

heap-sort/index.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const heapsort = arr => {
2+
const a = [...arr];
3+
let l = a.length;
4+
5+
const heapify = (a, i) => {
6+
const left = 2 * i + 1;
7+
const right = 2 * i + 2;
8+
let max = i;
9+
if (left < l && a[left] > a[max]) max = left;
10+
if (right < l && a[right] > a[max]) max = right;
11+
if (max !== i) {
12+
[a[max], a[i]] = [a[i], a[max]];
13+
heapify(a, max);
14+
}
15+
};
16+
17+
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
18+
for (i = a.length - 1; i > 0; i--) {
19+
[a[0], a[i]] = [a[i], a[0]];
20+
l--;
21+
heapify(a, 0);
22+
}
23+
return a;
24+
};

0 commit comments

Comments
 (0)