The Basics of Heaps
Heaps are complete binary trees that satisfy the heap property. There are two main types of heaps: min-heap and max-heap.
Min-Heap
In a min-heap, the parent node is smaller than or equal to its children. This ensures that the smallest element is at the root.
Max-Heap
Conversely, in a max-heap, the parent node is greater than or equal to its children, placing the largest element at the root.
Heap Operations
Heaps support key operations like insertion, deletion, and heapifying to maintain the heap property.
Insertion
void insert(int key) {
heapSize++;
int i = heapSize;
while (i > 1 && key < heap[parent(i)]) {
heap[i] = heap[parent(i)];
i = parent(i);
}
heap[i] = key;
}
Deletion
int deleteMin() {
int min = heap[1];
heap[1] = heap[heapSize];
heapSize--;
heapify(1);
return min;
}
Heap Sort Algorithm
Heap sort leverages the heap data structure to efficiently sort an array in ascending order.
void heapSort(int arr[], int n) {
buildMaxHeap(arr, n);
for (int i = n; i > 1; i--) {
swap(arr[1], arr[i]);
n--;
maxHeapify(arr, 1, n);
}
}
Heaps play a crucial role in priority queues and graph algorithms, showcasing their significance in various applications. Dive deeper into the world of heaps to unlock their full potential!
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.