Skip to content

Commit cd32c7d

Browse files
authored
JavaScript
1 parent c088541 commit cd32c7d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Heap Sort/heap_sort.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const heapify = (arr, n, m) => {
2+
let max = m,
3+
l = 2 * m + 1,
4+
r = 2 * m + 2;
5+
if (l < n && arr[max] < arr[l]) max = l;
6+
if (r < n && arr[max] < arr[r]) max = r;
7+
if (max != m) {
8+
[arr[max], arr[m]] = [arr[m], arr[max]];
9+
heapify(arr, n, max);
10+
}
11+
};
12+
13+
const HeapSort = (arr) => {
14+
let n = arr.length;
15+
for (let j = n; j >= 0; j--) heapify(arr, n, j);
16+
for (let i = n - 1; i >= 0; i--, n--) {
17+
[arr[0], arr[i]] = [arr[i], arr[0]];
18+
heapify(arr, i, 0);
19+
}
20+
};

0 commit comments

Comments
 (0)