Heap Data Structure
Heap Data Structure
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this
criteria, a heap can be of two types −
For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either of its children.
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.
We shall use the same example to demonstrate how a Max Heap is created. The procedure to create
Min Heap is similar but we go for min values instead of max values.
We are going to derive an algorithm for max heap by inserting one element at a time. At any point of
time, heap must maintain its property. While insertion, we also assume that we are inserting a node in
an already heapified tree.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be less than that
of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same input
sample that we used earlier.
Example
Following are the implementations of this operation in various programming languages −
Open Compiler
{
Heap* heap = createHeap(10);
insert(heap, 35);
insert(heap, 33);
insert(heap, 42);
insert(heap, 10);
insert(heap, 14);
insert(heap, 19);
insert(heap, 27);
insert(heap, 44);
insert(heap, 26);
insert(heap, 31);
printHeap(heap);
int max = extractMax(heap);
printf("Maximum element: %d\n", max);
return 0;
}
Output
Heap elements: 44 42 35 33 31 19 27 10 26 14
Maximum element: 44
Example
Following are the implementations of this operation in various programming languages −
Open Compiler
if (heap->size == 0) {
printf("Heap is empty. Cannot extract maximum element.\n");
return -1;
}
// Store the root element
int max = heap->array[0];
// Replace the root with the last element
heap->array[0] = heap->array[heap->size - 1];
heap->size--;
// Heapify the root
heapify(heap, 0);
return max;
}
// print the elements of the heap
void printHeap(Heap* heap)
{
for (int i = 0; i < heap->size; i++) {
printf("%d ", heap->array[i]);
}
printf("\n");
}
// Deallocate memory occupied by the heap
void destroyHeap(Heap* heap)
{
free(heap->array);
free(heap);
}
// Example usage of the heap
int main()
{
Heap* heap = createHeap(10);
insert(heap, 35);
insert(heap, 33);
insert(heap, 42);
insert(heap, 10);
insert(heap, 14);
insert(heap, 19);
insert(heap, 27);
insert(heap, 44);
insert(heap, 26);
insert(heap, 31);
printf("Heap elements before deletion: ");
Page 9 of 9
printHeap(heap);
// Deleting the maximum element in the heap
int max = deleteMax(heap);
printf("Maximum element: %d\n", max);
printf("Heap elements after deletion: ");
printHeap(heap);
destroyHeap(heap);
return 0;
}
Output
Heap elements before deletion: 44 42 35 33 31 19 27 10 26 14
Maximum element: 44
Heap elements after deletion: 42 33 35 26 31 19 27 10 14