-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathHeapSort.js
48 lines (35 loc) · 961 Bytes
/
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
var array_length;
function heapLarge(input, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
var large = i;
if (left < array_length && input[left] > input[large]) {
large = left;
}
if (right < array_length && input[right] > input[large]) {
large = right;
}
if (large != i) {
swap(input, i, large);
heapLarge(input, large);
}
}
function swap(input, index_A, index_B) {
var temp = input[index_A];
input[index_A] = input[index_B];
input[index_B] = temp;
}
function heapSort(input) {
array_length = input.length;
for (var i = Math.floor(array_length / 2); i >= 0; i -= 1) {
heapLarge(input, i);
}
for (i = input.length - 1; i > 0; i--) {
swap(input, 0, i);
array_length--;
heapLarge(input, 0);
}
}
var inputList = [-5, 3, 0, 2.5, -1.5, -1, 4, 1];
heapSort(inputList);
console.log(inputList);