SIGN IN SIGN UP

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices.

34081 0 0 JavaScript
2017-09-29 23:16:15 +02:00
/*
2020-05-05 17:41:32 +05:30
* 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"] }] */
2017-09-29 23:16:15 +02:00
Array.prototype.heapify = function (index, heapSize) {
2020-05-03 09:05:12 +02:00
let largest = index
const leftIndex = 2 * index + 1
const rightIndex = 2 * index + 2
2017-09-29 23:16:15 +02:00
if (leftIndex < heapSize && this[leftIndex] > this[largest]) {
2020-05-03 09:05:12 +02:00
largest = leftIndex
2017-09-29 23:16:15 +02:00
}
if (rightIndex < heapSize && this[rightIndex] > this[largest]) {
2020-05-03 09:05:12 +02:00
largest = rightIndex
2017-09-29 23:16:15 +02:00
}
if (largest !== index) {
2020-05-03 09:05:12 +02:00
const temp = this[largest]
this[largest] = this[index]
this[index] = temp
2017-09-29 23:16:15 +02:00
2020-05-03 09:05:12 +02:00
this.heapify(largest, heapSize)
2017-09-29 23:16:15 +02:00
}
2020-05-03 09:05:12 +02:00
}
2017-09-29 23:16:15 +02:00
/*
2020-05-05 17:41:32 +05:30
* 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) {
2020-05-03 09:05:12 +02:00
const length = items.length
2017-09-29 23:16:15 +02:00
2018-03-31 00:01:22 +02:00
for (let i = Math.floor(length / 2) - 1; i > -1; i--) {
2020-05-03 09:05:12 +02:00
items.heapify(i, length)
2017-09-29 23:16:15 +02:00
}
2020-05-03 09:05:12 +02:00
for (let j = length - 1; j > 0; j--) {
const tmp = items[0]
items[0] = items[j]
items[j] = tmp
items.heapify(0, j)
2017-09-29 23:16:15 +02:00
}
2020-05-03 09:05:12 +02:00
return items
2017-09-29 23:16:15 +02:00
}
2020-05-03 09:05:12 +02:00
// Implementation of heapSort
2017-09-29 23:16:15 +02:00
// const ar = [5, 6, 7, 8, 1, 2, 12, 14]
// heapSort(ar)