8000 Merge pull request #15 from Ditobaskoro/heapSort · AllAlgorithms/javascript@68ad56e · GitHub
[go: up one dir, main page]

Skip to content

Commit 68ad56e

Browse files
authored
Merge pull request #15 from Ditobaskoro/heapSort
Create Heap sort
2 parents 7a759c1 + d748954 commit 68ad56e

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

sorting/heapSort.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// JavaScript implementation of heap sort
2+
//
3+
// Author: Dito Baskoro
4+
5+
let array_length;
6+
/* to create MAX array */
7+
function heap_root(input, i) {
8+
let left = 2 * i + 1;
9+
let right = 2 * i + 2;
10+
let max = i;
11+
12+
if (left < array_length && input[left] > input[max]) {
13+
max = left;
14+
}
15+
16+
if (right < array_length && input[right] > input[max]) {
17+
max = right;
18+
}
19+
20+
if (max != i) {
21+
swap(input, i, max);
22+
heap_root(input, max);
23+
}
24+
}
25+
26+
function swap(input, index_A, index_B) {
27+
let temp = input[index_A];
28+
29+
input[index_A] = input[index_B];
30+
input[index_B] = temp;
31+
}
32+
33+
function heapSort(input) {
34+
35+
array_length = input.length;
36+
37+
for (let i = Math.floor(array_length / 2); i >= 0; i -= 1) {
38+
heap_root(input, i);
39+
}
40+
41+
for (i = input.length - 1; i > 0; i--) {
42+
swap(input, 0, i);
43+
array_length--;
44+
45+
46+
heap_root(input, 0);
47+
}
48+
}
49+
50+
const arr = [3, 0, 2, 5, -1, 4, 1, -2];
51+
heapSort(arr);
52+
console.log(arr);

0 commit comments

Comments
 (0)
0