forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSort.js
57 lines (46 loc) · 1.27 KB
/
HeapSort.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const MAX_LENGTH = 10;
/**
* @param {number[]} vector
*/
function heapSort(vector){
let length = vector.length;
let i = parseInt(vector.length / 2);
let temp, father, children;
while(true) {
if(i > 0){
i--;
temp = vector[i];
} else {
length--;
if (length <= 0) return vector;
temp = vector[length];
vector[length] = vector[0];
}
father = i;
children = parseInt((i * 2) + 1);
while(children < length) {
if (children + 1 < length && vector[children + 1] > vector[children])
children++;
if (vector[children] > temp) {
vector[father] = vector[children];
father = children;
children = parseInt(father * 2 + 1);
} else break;
}
vector[father] = temp;
}
}
function main(){
let vector = [];
let values = "[";
for (let index = 0; index < MAX_LENGTH; index++) {
let value = Math.floor(Math.random() * 99); // 0 - 99
vector.push(value);
values += `${value}, `;
}
values += "]"
console.log("Initial -> ", values);
console.log("Final Vector")
console.table(heapSort(vector));
}
main();