Skip to content

Commit ef714b1

Browse files
committed
HeapSort sorting algorithm in JS
1 parent a542f19 commit ef714b1

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

‎SortingAlgorithms/HeapSort.js‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//Language: Javascript
2+
//Author: Maria Luize
3+
//Github: https://github.com/MariaLuize
4+
5+
// Creating a max heap function
6+
function maxHeap(input, c) {
7+
const right = 2 * i + 2
8+
const left = 2 * i + 1
9+
let maximum = c
10+
11+
if ((left < arrLength) && (input[left] > input[maximum])) {
12+
maximum = left
13+
}
14+
15+
if ((right < arrLength) && (input[right] > input[maximum])) {
16+
maximum = right
17+
}
18+
19+
if (maximum != c) {
20+
swap(input, c, maximum)
21+
maxHeap(input, maximum)
22+
}
23+
}
24+
25+
//Function for swaping
26+
function swap(input, indexA, indexB) {
27+
const i = input[indexA]
28+
29+
input[indexA] = input[indexB]
30+
input[indexB] = i
31+
}
32+
33+
//The heapSort itself
34+
function heapSort(input) {
35+
arrLength = input.length
36+
37+
for (let i = Math.floor(arrLength / 2); i >= 0; i -= 1) {
38+
maxHeap(input, i)
39+
}
40+
41+
for (i = input.length - 1; i > 0; i--) {
42+
swap(input, 0, i)
43+
arrLength--
44+
45+
maxHeap(input, 0)
46+
}
47+
return
48+
}

0 commit comments

Comments
 (0)