Skip to content

Commit 76afeff

Browse files
committed
abc
1 parent 8358aed commit 76afeff

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Sorting/HeapSort/NodeJS/heapSort.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
addToHeap = (heap, newMember) => {
2+
return [...heap, newMember];
3+
}
4+
5+
heapify = (heap, currentIndex) => {
6+
while (true) {
7+
// this is heapsort algorithm in array
8+
// here is map function from index in arr to node in tree
9+
// 1
10+
// / \
11+
// 0 1
12+
// / \ / \
13+
// 0 1 0 1
14+
// array tree
15+
// 0 1
16+
// 1 10 = 2
17+
// 2 11 = 3
18+
// 3 100 = 4
19+
// 4 101 = 5
20+
// ..... ....
21+
// so the parentNode of a node is floor of (index/2)
22+
let parentNode = Math.floor(currentIndex / 2);
23+
if (parentNode !== 0) {
24+
// array begin with 0 and tree begin with 1 so we have to sub by 1
25+
if (heap[currentIndex-1] > heap[parentNode-1]) {
26+
[heap[currentIndex-1], heap[parentNode-1]] = [heap[parentNode-1], heap[currentIndex-1]];
27+
currentIndex = parentNode;
28+
} else {
29+
break;
30+
}
31+
} else {
32+
break;
33+
}
34+
}
35+
return heap;
36+
}
37+
38+
function main() {
39+
let arr = [10, 2, 7, 7, 9, 5, 3, 8, 1, 15];
40+
let ans = [];
41+
arr.forEach((number, index)=>{
42+
ans = addToHeap(ans, number);
43+
ans = heapify(ans, index+1);
44+
})
45+
console.log(ans);
46+
}
47+
48+
main();

0 commit comments

Comments
 (0)