Priority Queue Heap Data Structure
Priority Queue Heap Data Structure
All nodes in the tree follow the property that they are greater than
their children i.e. the largest element is at the root and both its
children and smaller than the root and so on. Such a heap is called a
max-heap. If instead, all nodes are smaller than their children, it is
called a min-heap
Since heapify uses recursion, it can be difficult to grasp. So let's first think
about how you would heapify a tree with just three elements.
Heapify base cases
The example above shows two scenarios - one in which the root is the
largest element and we don't need to do anything. And another in which
the root had a larger element as a child and we needed to swap to
maintain max-heap property.
Now let's think of another scenario in which there is more than one level.
How to heapify root element when its
subtrees are already max heaps
The top element isn't a max-heap but all the sub-trees are max-heaps.
To maintain the max-heap property for the entire tree, we will have to
keep pushing 2 downwards until it reaches its correct position.
How to
heapify
root element when its subtrees are max-heaps
This function works for both the base case and for a tree of any size. We
can thus move the root element to the correct position to maintain the
max-heap status for any tree size as long as the sub-trees are max-heaps.
Build max-heap
To build a max-heap from any tree, we can thus start heapifying each sub-
tree from the bottom up and end up with a max-heap after the function is
applied to all the elements including the root element.
In the case of a complete tree, the first index of a non-leaf node is given
by n/2 - 1. All other nodes after that are leaf-nodes and thus don't need to
be heapified.
heapify(arr, n, i);
1. Since the tree satisfies Max-Heap property, then the largest item is
stored at the root node.
2. Swap: Remove the root element and put at the end of the array
(nth position) Put the last item of the tree (heap) at the vacant
place.
5. The process is repeated until all the items of the list are sorted.
Swap, Remove, and Heapify
// Heap Sort in C
#include <stdio.h>
*a = *b;
*b = temp;
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
largest = left;
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
// Main function to do heap sort
heapify(arr, n, i);
// Heap sort
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
// Print an array
printf("\n");
// Driver code
int main() {
heapSort(arr, n);
printf("Sorted array is \n");
printArray(arr, n);