forked from JackPu/JavaScript-Algorithm-Learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap-sort.js
41 lines (36 loc) · 854 Bytes
/
heap-sort.js
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
41
/**
* heap sort O(nlogn) https://zh.wikipedia.org/wiki/%E5%A0%86%E6%8E%92%E5%BA%8F
**/
function heapSort(arr) {
// set the parent target and children target
let maxHelpify = function(arr, start, end) {
let dad = start;
let son = 2 * dad + 1;
while (son <= end) {
if (son + 1 <= end && arr[son] < arr[son + 1]) {
son++;
}
if (arr[dad] > arr[son]) {
return;
} else {
let tem = arr[son];
arr[son] = arr[dad];
arr[dad] = tem;
dad = son;
son = dad*2 +1;
}
}
}
let len = arr.length;
for(let i = Math.floor(len / 2 - 1);i>=0;i--){
maxHelpify(arr,i,len - 1);
}
for(let i = len - 1; i>0; i--) {
let tem = arr[i];
arr[i] = arr[0];
arr[0] = tem;
maxHelpify(arr,0,i - 1);
}
return arr;
}
module.exports = heapSort;