forked from vJechsmayr/JavaScriptAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.js
More file actions
48 lines (38 loc) · 986 Bytes
/
HeapSort.js
File metadata and controls
48 lines (38 loc) · 986 Bytes
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
//Language: Javascript
//Author: Maria Luize
//Github: https://github.com/MariaLuize
// Creating a max heap function
function maxHeap(input, c) {
const right = 2 * i + 2
const left = 2 * i + 1
let maximum = c
if ((left < arrLength) && (input[left] > input[maximum])) {
maximum = left
}
if ((right < arrLength) && (input[right] > input[maximum])) {
maximum = right
}
if (maximum != c) {
swap(input, c, maximum)
maxHeap(input, maximum)
}
}
//Function for swaping
function swap(input, indexA, indexB) {
const i = input[indexA]
input[indexA] = input[indexB]
input[indexB] = i
}
//The heapSort itself
function heapSort(input) {
arrLength = input.length
for (let i = Math.floor(arrLength / 2); i >= 0; i -= 1) {
maxHeap(input, i)
}
for (i = input.length - 1; i > 0; i--) {
swap(input, 0, i)
arrLength--
maxHeap(input, 0)
}
return
}