feat: Combined Min Heap and Max Heap classes (#1494)

* Combined Min Heap and Max Heap classes

* Added JSdoc comments and also improved tests for binary heap

* Added private methods for BinaryHeap class

* JSDoc knows that a class is a class

I assume the @class tag is for classes implemented via constructor functions, not using ES6 class syntax

---------

Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
Rohan
2023-10-10 12:44:34 +05:30
committed by GitHub
parent c5a25665e0
commit 13161bdadb
6 changed files with 231 additions and 251 deletions

View File

@ -0,0 +1,151 @@
/**
* BinaryHeap class represents a binary heap data structure that can be configured as a Min Heap or Max Heap.
*
* Binary heaps are binary trees that are filled level by level and from left to right inside each level.
* They have the property that any parent node has a smaller (for Min Heap) or greater (for Max Heap) priority
* than its children, ensuring that the root of the tree always holds the extremal value.
*/
class BinaryHeap {
/**
* Creates a new BinaryHeap instance.
* @constructor
* @param {Function} comparatorFunction - The comparator function used to determine the order of elements (e.g., minHeapComparator or maxHeapComparator).
*/
constructor(comparatorFunction) {
/**
* The heap array that stores elements.
* @member {Array}
*/
this.heap = []
/**
* The comparator function used for ordering elements in the heap.
* @member {Function}
*/
this.comparator = comparatorFunction
}
/**
* Inserts a new value into the heap.
* @param {*} value - The value to be inserted into the heap.
*/
insert(value) {
this.heap.push(value)
this.#bubbleUp(this.heap.length - 1)
}
/**
* Returns the number of elements in the heap.
* @returns {number} - The number of elements in the heap.
*/
size() {
return this.heap.length
}
/**
* Checks if the heap is empty.
* @returns {boolean} - True if the heap is empty, false otherwise.
*/
empty() {
return this.size() === 0
}
/**
* Bubbles up a value from the specified index to maintain the heap property.
* @param {number} currIdx - The index of the value to be bubbled up.
* @private
*/
#bubbleUp(currIdx) {
let parentIdx = Math.floor((currIdx - 1) / 2)
while (
currIdx > 0 &&
this.comparator(this.heap[currIdx], this.heap[parentIdx])
) {
this.#swap(currIdx, parentIdx)
currIdx = parentIdx
parentIdx = Math.floor((currIdx - 1) / 2)
}
}
/**
* Sinks down a value from the specified index to maintain the heap property.
* @param {number} currIdx - The index of the value to be sunk down.
* @private
*/
#sinkDown(currIdx) {
let childOneIdx = currIdx * 2 + 1
while (childOneIdx < this.size()) {
const childTwoIdx = childOneIdx + 1 < this.size() ? childOneIdx + 1 : -1
const swapIdx =
childTwoIdx !== -1 &&
this.comparator(this.heap[childTwoIdx], this.heap[childOneIdx])
? childTwoIdx
: childOneIdx
if (this.comparator(this.heap[swapIdx], this.heap[currIdx])) {
this.#swap(currIdx, swapIdx)
currIdx = swapIdx
childOneIdx = currIdx * 2 + 1
} else {
return
}
}
}
/**
* Retrieves the top element of the heap without removing it.
* @returns {*} - The top element of the heap.
*/
peek() {
return this.heap[0]
}
/**
* Removes and returns the top element of the heap.
* @returns {*} - The top element of the heap.
*/
extractTop() {
const top = this.peek()
const last = this.heap.pop()
if (!this.empty()) {
this.heap[0] = last
this.#sinkDown(0)
}
return top
}
/**
* Swaps elements at two specified indices in the heap.
* @param {number} index1 - The index of the first element to be swapped.
* @param {number} index2 - The index of the second element to be swapped.
* @private
*/
#swap(index1, index2) {
;[this.heap[index1], this.heap[index2]] = [
this.heap[index2],
this.heap[index1]
]
}
}
/**
* Comparator function for creating a Min Heap.
* @param {*} a - The first element to compare.
* @param {*} b - The second element to compare.
* @returns {boolean} - True if 'a' should have higher priority than 'b' in the Min Heap, false otherwise.
*/
const minHeapComparator = (a, b) => a < b
/**
* Comparator function for creating a Max Heap.
* @param {*} a - The first element to compare.
* @param {*} b - The second element to compare.
* @returns {boolean} - True if 'a' should have higher priority than 'b' in the Max Heap, false otherwise.
*/
const maxHeapComparator = (a, b) => a > b
export { BinaryHeap, minHeapComparator, maxHeapComparator }

View File

@ -1,85 +0,0 @@
/**
* Author: Samarth Jain
* Max Heap implementation in Javascript
*/
class BinaryHeap {
constructor() {
this.heap = []
}
insert(value) {
this.heap.push(value)
this.heapify()
}
size() {
return this.heap.length
}
empty() {
return this.size() === 0
}
// using iterative approach to reorder the heap after insertion
heapify() {
let index = this.size() - 1
while (index > 0) {
const element = this.heap[index]
const parentIndex = Math.floor((index - 1) / 2)
const parent = this.heap[parentIndex]
if (parent[0] >= element[0]) break
this.heap[index] = parent
this.heap[parentIndex] = element
index = parentIndex
}
}
// Extracting the maximum element from the Heap
extractMax() {
const max = this.heap[0]
const tmp = this.heap.pop()
if (!this.empty()) {
this.heap[0] = tmp
this.sinkDown(0)
}
return max
}
// To restore the balance of the heap after extraction.
sinkDown(index) {
const left = 2 * index + 1
const right = 2 * index + 2
let largest = index
const length = this.size()
if (left < length && this.heap[left][0] > this.heap[largest][0]) {
largest = left
}
if (right < length && this.heap[right][0] > this.heap[largest][0]) {
largest = right
}
// swap
if (largest !== index) {
const tmp = this.heap[largest]
this.heap[largest] = this.heap[index]
this.heap[index] = tmp
this.sinkDown(largest)
}
}
}
// Example
// const maxHeap = new BinaryHeap()
// maxHeap.insert([4])
// maxHeap.insert([3])
// maxHeap.insert([6])
// maxHeap.insert([1])
// maxHeap.insert([8])
// maxHeap.insert([2])
// const mx = maxHeap.extractMax()
export { BinaryHeap }

View File

@ -1,127 +0,0 @@
/**
* Min Heap is one of the two Binary Heap types (the other is Max Heap)
* which maintains the smallest value of its input array on top and remaining values in loosely (but not perfectly sorted) order.
*
* Min Heaps can be expressed as a 'complete' binary tree structure
* (in which all levels of the binary tree are filled, with the exception of the last level which must be filled left-to-right).
*
* However the Min Heap class below expresses this tree structure as an array
* which represent the binary tree node values in an array ordered from root-to-leaf, left-to-right.
*
* In the array representation, the parent node-child node relationship is such that the
* * parent index relative to its two children are: (parentIdx * 2) and (parent * 2 + 1)
* * and either child's index position relative to its parent is: Math.floor((childIdx-1)/2)
*
* The parent and respective child values define much of heap behavior as we continue to sort or not sort depending on their values.
* * The parent value must be less than or equal to either child's value.
*
* This is a condensed overview but for more information and visuals here is a nice read: https://www.geeksforgeeks.org/binary-heap/
*/
class MinHeap {
constructor(array) {
this.heap = this.initializeHeap(array)
}
/**
* startingParent represents the parent of the last index (=== array.length-1)
* and iterates towards 0 with all index values below sorted to meet heap conditions
*/
initializeHeap(array) {
const startingParent = Math.floor((array.length - 2) / 2)
for (let currIdx = startingParent; currIdx >= 0; currIdx--) {
this.sinkDown(currIdx, array.length - 1, array)
}
return array
}
/**
* overall functionality: heap-sort value at a starting index (currIdx) towards end of heap
*
* currIdx is considered to be a starting 'parent' index of two children indices (childOneIdx, childTwoIdx).
* endIdx represents the last valid index in the heap.
*
* first check that childOneIdx and childTwoIdx are both smaller than endIdx
* and check for the smaller heap value between them.
*
* the child index with the smaller heap value is set to a variable called swapIdx.
*
* swapIdx's value will be compared to currIdx (the 'parent' index)
* and if swapIdx's value is smaller than currIdx's value, swap the values in the heap,
* update currIdx and recalculate the new childOneIdx to check heap conditions again.
*
* if there is no swap, it means the children indices and the parent index satisfy heap conditions and can exit the function.
*/
sinkDown(currIdx, endIdx, heap) {
let childOneIdx = currIdx * 2 + 1
while (childOneIdx <= endIdx) {
const childTwoIdx = childOneIdx + 1 <= endIdx ? childOneIdx + 1 : -1
const swapIdx =
childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]
? childTwoIdx
: childOneIdx
if (heap[swapIdx] < heap[currIdx]) {
this.swap(currIdx, swapIdx, heap)
currIdx = swapIdx
childOneIdx = currIdx * 2 + 1
} else {
return
}
}
}
/**
* overall functionality: heap-sort value at a starting index (currIdx) towards front of heap.
*
* while the currIdx's value is smaller than its parent's (parentIdx) value, swap the values in the heap
* update currIdx and recalculate the new parentIdx to check heap condition again.
*
* iteration does not end while a valid currIdx has a value smaller than its parentIdx's value
*/
bubbleUp(currIdx) {
let parentIdx = Math.floor((currIdx - 1) / 2)
while (currIdx > 0 && this.heap[currIdx] < this.heap[parentIdx]) {
this.swap(currIdx, parentIdx, this.heap)
currIdx = parentIdx
parentIdx = Math.floor((currIdx - 1) / 2)
}
}
peek() {
return this.heap[0]
}
/**
* the min heap value should be the first value in the heap (=== this.heap[0])
*
* firstIdx value and lastIdx value are swapped
* the resulting min heap value now resides at heap[heap.length-1] which is popped and later returned.
*
* the remaining values in the heap are re-sorted
*/
extractMin() {
this.swap(0, this.heap.length - 1, this.heap)
const min = this.heap.pop()
this.sinkDown(0, this.heap.length - 1, this.heap)
return min
}
// a new value is pushed to the end of the heap and sorted up
insert(value) {
this.heap.push(value)
this.bubbleUp(this.heap.length - 1)
}
// index-swapping helper method
swap(idx1, idx2, heap) {
const temp = heap[idx1]
heap[idx1] = heap[idx2]
heap[idx2] = temp
}
}
export { MinHeap }

View File

@ -0,0 +1,72 @@
import { BinaryHeap, minHeapComparator } from '../BinaryHeap'
describe('BinaryHeap', () => {
describe('MinHeap', () => {
let minHeap
beforeEach(() => {
// Initialize a MinHeap
minHeap = new BinaryHeap(minHeapComparator)
minHeap.insert(4)
minHeap.insert(3)
minHeap.insert(6)
minHeap.insert(1)
minHeap.insert(8)
minHeap.insert(2)
})
it('should initialize a heap from an input array', () => {
// Check if the heap is initialized correctly
expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6])
})
it('should show the top value in the heap', () => {
// Check if the top value is as expected
const minValue = minHeap.peek()
expect(minValue).toEqual(1)
})
it('should remove and return the top value in the heap', () => {
// Check if the top value is removed correctly
const minValue = minHeap.extractTop()
expect(minValue).toEqual(1)
expect(minHeap.heap).toEqual([2, 3, 6, 4, 8])
})
it('should handle insertion of duplicate values', () => {
// Check if the heap handles duplicate values correctly
minHeap.insert(2)
console.log(minHeap.heap);
expect(minHeap.heap).toEqual([1, 3, 2, 4, 8, 6, 2])
})
it('should handle an empty heap', () => {
// Check if an empty heap behaves as expected
const emptyHeap = new BinaryHeap(minHeapComparator)
expect(emptyHeap.peek()).toBeUndefined()
expect(emptyHeap.extractTop()).toBeUndefined()
})
it('should handle extracting all elements from the heap', () => {
// Check if all elements can be extracted in the correct order
const extractedValues = []
while (!minHeap.empty()) {
extractedValues.push(minHeap.extractTop())
}
expect(extractedValues).toEqual([1, 2, 3, 4, 6, 8])
})
it('should insert elements in ascending order', () => {
// Check if elements are inserted in ascending order
const ascendingHeap = new BinaryHeap(minHeapComparator)
ascendingHeap.insert(4)
ascendingHeap.insert(3)
ascendingHeap.insert(2)
ascendingHeap.insert(1)
expect(ascendingHeap.extractTop()).toEqual(1)
expect(ascendingHeap.extractTop()).toEqual(2)
expect(ascendingHeap.extractTop()).toEqual(3)
expect(ascendingHeap.extractTop()).toEqual(4)
})
})
})

View File

@ -1,37 +0,0 @@
import { MinHeap } from '../MinHeap'
describe('MinHeap', () => {
const array = [2, 4, 10, 23, 43, 42, 39, 7, 9, 16, 85, 1, 51]
let heap
beforeEach(() => {
heap = new MinHeap(array)
})
it('should initialize a heap from an input array', () => {
expect(heap).toEqual({
heap: [1, 4, 2, 7, 16, 10, 39, 23, 9, 43, 85, 42, 51]
}) // eslint-disable-line
})
it('should show the top value in the heap', () => {
const minValue = heap.peek()
expect(minValue).toEqual(1)
})
it('should remove and return the top value in the heap', () => {
const minValue = heap.extractMin()
expect(minValue).toEqual(1)
expect(heap).toEqual({ heap: [2, 4, 10, 7, 16, 42, 39, 23, 9, 43, 85, 51] }) // eslint-disable-line
})
it('should insert a new value and sort until it meets heap conditions', () => {
heap.insert(15)
expect(heap).toEqual({
heap: [2, 4, 10, 7, 16, 15, 39, 23, 9, 43, 85, 51, 42]
}) // eslint-disable-line
})
})

View File

@ -2,11 +2,17 @@ import { EuclideanDistance } from '../EuclideanDistance.js'
describe('EuclideanDistance', () => {
it('should calculate the distance correctly for 2D vectors', () => {
expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10)
expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(
2.8284271247461903,
10
)
})
it('should calculate the distance correctly for 3D vectors', () => {
expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10)
expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(
3.4641016151377544,
10
)
})
it('should calculate the distance correctly for 4D vectors', () => {