A heap is a specialized tree-based data structure that satisfies the heap property. The heap property is defined differently for min-heaps and max-heaps:
Heaps are often used to implement priority queues, where elements with higher (or lower, depending on whether it's a min-heap or max-heap) priority are processed before others. The heap data structure allows for efficient insertion, deletion, and retrieval of the element with the highest (or lowest) priority.
Heaps are typically implemented as binary trees, specifically binary heap trees, because they provide efficient operations and can be efficiently represented using an array. Binary heaps can be categorized into two main types:
Common operations performed on heaps include:
Heaps are widely used in algorithms such as heap sort, Dijkstra's shortest path algorithm, and priority queue implementations. They offer efficient solutions to various problems where elements need to be prioritized and processed in a specific order.
Lets write code for Minheap in Javascript:
We are going to write a min heap so that we get the behavior stated beside.
Create class Minheap which has an array called heap in its constructor. This Class has the following functions:
const minHeap = new MinHeap();
minHeap.push(4);
minHeap.push(9);
minHeap.push(2);
minHeap.push(1);
minHeap.push(5);
console.log(minHeap.heap); // [1, 2, 4, 9, 5]
console.log(minHeap.pop()); // 1
console.log(minHeap.heap); // [2, 5, 4, 9]
class MinHeap {
constructor() {
this.heap = [];
}
// Function to insert a new element into the heap
push(value) { }
// Function to extract the minimum element from the heap
pop() { }
// Function to get the index of the parent node
parentIndex(index) { }
// Function to maintain the min-heap property by moving the newly inserted element up
heapifyUp() { }
// Function to maintain the min-heap property by moving the root element down
heapifyDown() { }
}
Kth Smallest Element in a sorted Matrix