Skip to content

Commit 2d7d2c7

Browse files
committed
heap sort using binary heap
1 parent 67715f0 commit 2d7d2c7

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'use strict';
2+
function heapify(arr, rootIndex, n) {
3+
let largetIndex = rootIndex;
4+
let leftIndex = (rootIndex * 2) + 1;
5+
let rightIndex = (rootIndex * 2) + 2;
6+
if (leftIndex < n && arr[largetIndex] < arr[leftIndex]) largetIndex = leftIndex;
7+
if (rightIndex < n && arr[largetIndex] < arr[rightIndex]) largetIndex = rightIndex;
8+
if (largetIndex != rootIndex) {
9+
let temp = arr[rootIndex];
10+
arr[rootIndex] = arr[largetIndex];
11+
arr[largetIndex] = temp;
12+
heapify(arr, largetIndex, n);
13+
}
14+
}
15+
16+
function heapSort(array) {
17+
for (let index = 0; index < array.length; index++)
18+
heapify(array, index, array.length);
19+
20+
for (let index = 0; index < array.length; index++) {
21+
heapify(array, 0, array.length - index);
22+
let temp = array[0];
23+
array[0] = array[array.length - 1 - index];
24+
array[array.length - 1 - index] = temp;
25+
}
26+
console.log('Heap Sort - ', array.join(', '));
27+
}
28+
29+
let array = [3, 5, 1, 8, 2, 4, 10, 12];
30+
heapSort(array);

0 commit comments

Comments
 (0)