-
Notifications
You must be signed in to change notification settings - Fork 108
/
HeapSort.js
50 lines (44 loc) · 965 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
49
50
function heapSort(arr){
var len = arr.length,
end = len-1;
heapify(arr, len);
while(end > 0){
swap(arr, end--, 0);
DownHeapify(arr, 0, end);
}
return arr;
}
function heapify(arr, len){
// breaking the array into root + two sides, to create tree (heap)
var mid = Math.floor((len-2)/2);
while(mid >= 0){
DownHeapify(arr, mid--, len-1);
}
}
function DownHeapify(arr, start, end){
var root = start,
child = root*2 + 1,
toSwap = root;
while(child <= end){
if(arr[toSwap] < arr[child]){
swap(arr, toSwap, child);
}
if(child+1 <= end && arr[toSwap] < arr[child+1]){
swap(arr, toSwap, child+1)
}
if(toSwap != root){
swap(arr, root, toSwap);
root = toSwap;
}
else{
return;
}
toSwap = root;
child = root*2+1
}
}
function swap(arr, i, j){
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}