Heap
Description:
Heap data structure are basically binary trees with a very specific condition. Depending if the Heap is a Max Heap or a Min Heap the tree is going to have the elements on top being the largest ones or the smallest ones.
Pros & Cons:
Using this data structure has some benefits, such as:
Is really easy to find min or max: heaps stores the smallest or largest values on the top nodes, so if we want to find those is going to be pretty fast.
It also has some cons, for example:
Is not optimal for random searches: for how the structure stores the data, is not a particular order so finding an element is going to be slow.
1. Class data and Constructor implementation:
0
1
2
3
4
5
6
7
8
data: number[];
minHeap: boolean; // We are using this to know if it is a MaxHeap or a MinHeap
constructor(array: number[], minHeap: boolean = false) {
this.data = array;
this.minHeap = minHeap;
this.buildHeap();
}
2. Heapify:
0
1
2
3
4
5
6
7
8
data: number[];
minHeap: boolean; // We are using this to know if it is a MaxHeap or a MinHeap
constructor(array: number[], minHeap: boolean = false) {
this.data = array;
this.minHeap = minHeap;
this.buildHeap();
}
Testing it
So, we are going to test in console to see if it is working. We are going to run the following:
0
1
You should see something like the following in the console:
0
1