-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminHeapSort.js
More file actions
40 lines (28 loc) · 756 Bytes
/
minHeapSort.js
File metadata and controls
40 lines (28 loc) · 756 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function minHeap(array){
for(let i=Math.floor(array.length/2)-1;i>=0;i--){
heapify(array,i,array.length)
}
for(let i=array.length-1;i>0;i--){
[array[0],array[i]]=[array[i],array[0]]
heapify(array,0,i)
}
return array
}
function heapify(array,i,length){
let largest=i
let leftchild=i*2+1
let rightchild=i*2+2
if(leftchild<length&&array[leftchild]>array[largest]){
largest=leftchild
}
if(rightchild<length&&array[rightchild]>array[largest]){
largest=rightchild
}
if(largest!==i){
[array[i],array[largest]]=[array[largest],array[i]]
heapify(array,largest,length)
}
}
let array=[2,6,4,8,5,9]
let res=heap(array)
console.log(res);