A heap is a specialized tree-based data structure which is essentially an almost complete tree that satisfies the heap property :in a max heap, for any given node C, if P is a parent node of C, then the key (the value) of P is greater than or equal to the key of C. In a min heap, the key of P is less than or equal to the key of C. The node at the "top" of the heap (with no parents) is called the root node.
Install with npm
npm i javascript-algo-ds
Import in your javascript file as:
const Heap = require('javascript-algo-ds/src/data-structure/heap/heap')
const MinHeap = require('javascript-algo-ds/src/data-structure/heap/minHeap')
const MaxHeap = require('javascript-algo-ds/src/data-structure/heap/maxHeap')const minHeap = new MinHeap(compareFunc)
const maxHeap = new MaxHeap(compareFunc)- compareFunction - function
- Default value - undefined
- heap - array of objects in ordered way
- size - number of elements in the heap
- compare - comparator of type Comparator
- heap.isEmpty()
- heap.add(item)
- heap.peek()
- heap.poll()
- heap.remove(item)
- heap.find(item)
- heap.toString()
Checks if the heap contains at least one element or not.
Returns boolean
Adds item to the heap followed by heapifying.
- item - T
- The value to be added.
Returns this
Returns the element at root of the heap.
Type - T | null
Remove and returns the element at root of the heap followed by heapifying.
Type - T | null
- item - T
- The item to be removed.
Remove the element matching
itemusing custom compare function (if passed) at root of the heap followed by heapifying.
- The item to be removed.
Remove the element matching
Type - this
Finds the element matching item using custom compare function (if passed) and returns their indices in heap.heap array.
- item - T
- The item to be found.
Type - number[]
Converts the heap in array and returns it
Type - String
@static
Creates the heap from an array
- array - T[]
- Array of objects
- compareFunction - function
- Default value - undefined
Type - MinHeap | MaxHeap | Heap