Skip to content

Commit ba28e61

Browse files
authored
feat: add heap sort in javascript (#815)
1 parent f46ffd0 commit ba28e61

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

basic/sorting/HeapSort/Main.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function swap(arr, i, j) {
2+
const temp = arr[i];
3+
arr[i] = arr[j];
4+
arr[j] = temp;
5+
}
6+
7+
function heapify(arr, n, i) {
8+
if (i >= n) return;
9+
const c1 = 2 * i + 1;
10+
const c2 = 2 * i + 2;
11+
let largest = i;
12+
if (c1 < n && arr[c1] > arr[largest]) {
13+
largest = c1;
14+
}
15+
if (c2 < n && arr[c2] > arr[largest]) {
16+
largest = c2;
17+
}
18+
if (largest !== i) {
19+
swap(arr, i, largest);
20+
heapify(arr, n, largest);
21+
}
22+
}
23+
24+
25+
function buildHeap(arr, n) {
26+
const lastNode = n - 1;
27+
const lastParent = Math.floor((lastNode - 1) / 2);
28+
for (let i = lastParent; i >= 0; i--) {
29+
heapify(arr, n, i);
30+
}
31+
}
32+
33+
function heapSort(arr, n) {
34+
buildHeap(arr, n);
35+
for (let i = n - 1; i >= 0; i--) {
36+
swap(arr, i, 0);
37+
heapify(arr, i, 0);
38+
}
39+
}
40+
41+
function main(arr, n, m) {
42+
heapSort(arr, n);
43+
const list = arr.slice(0, m)
44+
console.log(list.join(' '));
45+
}

0 commit comments

Comments
 (0)