-
Notifications
You must be signed in to change notification settings - Fork 91
/
heapSort.js
49 lines (39 loc) · 1.02 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
// Testing Gist
var heapSort = function(arr) {
var n = arr.length;
for(let i = Math.floor(n/2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for(let i = n - 1; i >= 0; i--) {
swap(arr, 0, i);
heapify(arr, i, 0);
}
return arr;
};
var heapify = function(arr, n, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
if(left >= n && right >= n)
return;
const leftValue = (left >= n) ? Number.NEGATIVE_INFINITY : arr[left];
const rightValue = (right >= n) ? Number.NEGATIVE_INFINITY : arr[right];
if(arr[i] > leftValue && arr[i] > rightValue)
return;
if(leftValue > rightValue) {
swap(arr, i, left);
heapify(arr, n, left);
} else {
swap(arr, i, right);
heapify(arr, n, right);
}
};
var swap = function(arr, a, b) {
var temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
};
console.log(heapSort([14, 1, 10, 2, 3, 5, 6, 4, 7, 11, 12, 13]));
console.log(heapSort([]));
console.log(heapSort([1]));
console.log(heapSort([2, 1]));
console.log(heapSort([1,7,2,3,4,1,10,2,3,4,5]));