-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
38 lines (34 loc) · 1.07 KB
/
index.ts
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
const heapSort = (array?: Array<number>) : Array<number> => {
const len = array.length;
let heapsize = len;
const heapify = (index: number) => {
let current = array[index];
let largestIndex = index;
while(true){
let leftIndex = 2 * index + 1;
let rightIndex = leftIndex + 1;
if(leftIndex < heapsize && array[leftIndex] > current)
largestIndex = leftIndex
if(rightIndex < heapsize && array[rightIndex] > array[largestIndex])
largestIndex = rightIndex
if(largestIndex !== index){
array[index] = array[largestIndex];
array[largestIndex] = current;
index = largestIndex;
}
else
break;
}
}
for(let i=Math.floor(len/2)-1; i>=0; i--)
heapify(i);
for(let i=len-1; i>0; i--){
const temp = array[0];
array[0] = array[i];
array[i] = temp;
heapsize --;
heapify(0);
}
return array;
}
export default heapSort