mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
55 lines
1.4 KiB
JavaScript
55 lines
1.4 KiB
JavaScript
/*
|
|
* Build a max heap out of the array. A heap is a specialized tree like
|
|
* data structure that satisfies the heap property. The heap property
|
|
* for max heap is the following: "if P is a parent node of C, then the
|
|
* key (the value) of node P is greater than the key of node C"
|
|
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
|
|
*/
|
|
/* eslint no-extend-native: ["off", { "exceptions": ["Object"] }] */
|
|
Array.prototype.heapify = function (index, heapSize) {
|
|
let largest = index
|
|
const leftIndex = 2 * index + 1
|
|
const rightIndex = 2 * index + 2
|
|
|
|
if (leftIndex < heapSize && this[leftIndex] > this[largest]) {
|
|
largest = leftIndex
|
|
}
|
|
|
|
if (rightIndex < heapSize && this[rightIndex] > this[largest]) {
|
|
largest = rightIndex
|
|
}
|
|
|
|
if (largest !== index) {
|
|
const temp = this[largest]
|
|
this[largest] = this[index]
|
|
this[index] = temp
|
|
|
|
this.heapify(largest, heapSize)
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Heap sort sorts an array by building a heap from the array and
|
|
* utilizing the heap property.
|
|
* For more information see: https://en.wikipedia.org/wiki/Heapsort
|
|
*/
|
|
export function heapSort(items) {
|
|
const length = items.length
|
|
|
|
for (let i = Math.floor(length / 2) - 1; i > -1; i--) {
|
|
items.heapify(i, length)
|
|
}
|
|
for (let j = length - 1; j > 0; j--) {
|
|
const tmp = items[0]
|
|
items[0] = items[j]
|
|
items[j] = tmp
|
|
items.heapify(0, j)
|
|
}
|
|
return items
|
|
}
|
|
|
|
// Implementation of heapSort
|
|
|
|
// const ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
|
// heapSort(ar)
|