mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-20 18:43:43 +08:00

* HeapSort algorithm * Create QuickSelect.js * Algorithm to reverse a string. * Update ReverseString.js * Update Heapsort.js * Update QuickSelect.js Co-authored-by: vinayak <itssvinayak@gmail.com>
49 lines
836 B
JavaScript
49 lines
836 B
JavaScript
let arrayLength = 0
|
|
|
|
/* to create MAX array */
|
|
|
|
function heapRoot (input, i) {
|
|
const left = 2 * i + 1
|
|
const right = 2 * i + 2
|
|
let max = i
|
|
|
|
if (left < arrayLength && input[left] > input[max]) {
|
|
max = left
|
|
}
|
|
|
|
if (right < arrayLength && input[right] > input[max]) {
|
|
max = right
|
|
}
|
|
|
|
if (max !== i) {
|
|
swap(input, i, max)
|
|
heapRoot(input, max)
|
|
}
|
|
}
|
|
|
|
function swap (input, indexA, indexB) {
|
|
const temp = input[indexA]
|
|
|
|
input[indexA] = input[indexB]
|
|
input[indexB] = temp
|
|
}
|
|
|
|
function heapSort (input) {
|
|
arrayLength = input.length
|
|
|
|
for (let i = Math.floor(arrayLength / 2); i >= 0; i -= 1) {
|
|
heapRoot(input, i)
|
|
}
|
|
|
|
for (let i = input.length - 1; i > 0; i--) {
|
|
swap(input, 0, i)
|
|
arrayLength--
|
|
|
|
heapRoot(input, 0)
|
|
}
|
|
}
|
|
|
|
const arr = [3, 0, 2, 5, -1, 4, 1]
|
|
heapSort(arr)
|
|
console.log(arr)
|