forked from VAR-solutions/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapsort.js
More file actions
73 lines (60 loc) · 1.15 KB
/
heapsort.js
File metadata and controls
73 lines (60 loc) · 1.15 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Example
*/
arr = [1,4,3,-0,-9,12];
heapSort(arr);
console.log(arr);
/*
* Swap array elements
*/
function swap(arr, firstItemIndex, lastItemIndex) {
var temp = arr[firstItemIndex];
arr[firstItemIndex] = arr[lastItemIndex];
arr[lastItemIndex] = temp;
}
/*
* Sort elements by comparing values
*/
function heapify(arr, i, max) {
var index, leftChild, rightChild;
while (i < max) {
index = i;
leftChild = 2 * i + 1;
rightChild = leftChild + 1;
if (leftChild < max && arr[leftChild] > arr[index]) {
index = leftChild;
}
if (rightChild < max && arr[rightChild] > arr[index]) {
index = rightChild;
}
if (index === i) {
return;
}
swap(arr, i, index);
i = index;
}
}
/*
* convert list in to max heap
*/
function buildMaxHeap(arr) {
var i;
i = arr.length / 2 - 1;
i = Math.floor(i);
while (i >= 0) {
heapify(arr, i, arr.length);
i -= 1;
}
}
/*
* Steps for heap sort
*/
function heapSort(arr) {
buildMaxHeap(arr);
lastElement = arr.length - 1;
while (lastElement > 0) {
swap(arr, 0, lastElement);
heapify(arr, 0, lastElement);
lastElement -= 1;
}
}