new MinHeap()
In computer science, a heap is a specialized tree-based data
structure that satisfies the heap property: if P is a parent node of C, then the
key (the value) of P is either greater than or equal to (in a max heap) or less
than or equal to (in a min heap) the key of C.[1] The node at the "top" of the
heap (with no parents) is called the root node. Full wikipedia article at:
https://en.wikipedia.org/wiki/Heap_(data_structure)
- Source:
Example
const MinHeap = require('dstructures').MinHeap;
const myMinHeap = new MinHeap();
Methods
insert(element, priorityopt) → {Boolean|Void}
Inserts element in a heap.
- Source:
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
element |
any
|
Given element. | ||
priority |
Number
|
<optional> |
0 | Priority defaults to 0 if is not present. |
Returns:
- Type:
-
Boolean
|Void
Returns false if 'priority' is not number or
'element' is undefined or null.
Example
MinHeap.insert('Cat', 1); // ['Cat']
MinHeap.insert('Dog', 2); // ['Dog', 'Cat']
isEmpty() → {Boolean}
Checks if a heap is empty.
- Source:
Returns:
- Type:
-
Boolean
Returns true if a heap is empty,
otherwise fasle.
Example
MinHeap.isEmpty(); // true
MinHeap.insert('Cat', 1); // ['Cat']
MinHeap.isEmpty(); // false
peek() → {Boolean|Any}
Returns the top element in a heap.
- Source:
Returns:
- Type:
-
Boolean
|Any
Returns false if a heap is
empty, otherwise the top element in a heap.
Example
MinHeap.insert('Cat', 1); // ['Cat']
MinHeap.insert('Dog', 2); // ['Dog', 'Cat']
MinHeap.insert('Fox', 3); // ['Fox', 'Dog', 'Cat']
MinHeap.peek(); // 'Fox', ['Fox', 'Dog', 'Cat']
remove() → {Boolean|Any}
Removes and returns the top element in a heap
(the element with most priority).
- Source:
Returns:
- Type:
-
Boolean
|Any
Returns false if a heap is
empty, otherwise the top element in a heap.
Example
MinHeap.insert('Cat', 1); // ['Cat']
MinHeap.insert('Dog', 2); // ['Dog', 'Cat']
MinHeap.insert('Fox', 3); // ['Fox', 'Dog', 'Cat']
MinHeap.remove(); // ['Dog', 'Cat']
toArray() → {Array}
Returns array representation of a heap.
- Source:
Returns:
- Type:
-
Array
Returns array representation of a heap.