A heap is a specialized tree-based data structure that satisfies the heap property, which ensures that for any given node \( i \), the value of \( i \) is greater than or equal to (in a max heap) or less than or equal to (in a min heap) the values of its children. This property allows heaps to efficiently implement priority queues and perform operations like insertion, deletion, and finding the maximum or minimum element in logarithmic time.
\( i \), the value of \( i \) is greater than or equal to the values of its children.\( i \), the value of \( i \) is less than or equal to the values of its children.Heaps are typically represented as binary trees but can also be implemented using arrays. The array representation makes it easy to calculate the parent and child indices:
\( i \), the parent is at index \( \lfloor (i - 1) / 2 \rfloor \).\( i \), the left child is at index \( 2i + 1 \).\( i \), the right child is at index \( 2i + 2 \).To insert an element into a heap, follow these steps:
function insert(heap, value) {
heap.push(value);
let index = heap.length - 1;
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (heap[parentIndex] >= value) break;
[heap[index], heap[parentIndex]] = [heap[parentIndex], heap[index]];
index = parentIndex;
}
}
To delete the root element from a max heap, follow these steps:
function extractMax(heap) {
const max = heap[0];
const end = heap.pop();
if (heap.length > 0) {
heap[0] = end;
let index = 0;
const length = heap.length;
const element = heap[0];
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let leftChild, rightChild;
let swap = null;
if (leftChildIndex < length) {
leftChild = heap[leftChildIndex];
if (leftChild > element) {
swap = leftChildIndex;
}
}
if (rightChildIndex < length) {
rightChild = heap[rightChildIndex];
if (
(swap === null && rightChild > element) ||
(swap !== null && rightChild > leftChild)
) {
swap = rightChildIndex;
}
}
if (swap === null) break;
[heap[index], heap[swap]] = [heap[swap], heap[index]];
index = swap;
}
}
return max;
}
Heaps are powerful data structures that provide efficient ways to manage and retrieve elements based on priority. Understanding their properties, operations, and applications is crucial for any software engineer or data scientist working with algorithms and data management systems. By mastering heaps, you can optimize your code for better performance in various computational tasks.