0% found this document useful (0 votes)
2 views

Heap Data Structure

The document explains the Heap data structure, specifically focusing on Max Heap and Min Heap, including their properties and construction algorithms. It provides a detailed algorithm for inserting and deleting elements in a Max Heap, along with example implementations in C. Additionally, it includes sample outputs demonstrating heap operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Heap Data Structure

The document explains the Heap data structure, specifically focusing on Max Heap and Min Heap, including their properties and construction algorithms. It provides a detailed algorithm for inserting and deleting elements in a Max Heap, along with example implementations in C. Additionally, it includes sample outputs demonstrating heap operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Page 1 of 9

Heap Data Structure


Heap is a special case of balanced binary tree data structure where the root-node key is compared with
its children and arranged accordingly. If α has child node β then −

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.

Max Heap Construction Algorithm


Page 2 of 9

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.

Step 1 − Create a new node at the end of heap.


Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

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 −

C C++ Java Python

Open Compiler

//C code for Max Heap construction Algorithm


#include <stdio.h>
#include <stdlib.h>
Page 3 of 9

// Structure to represent a heap


typedef struct {
int* array; // Array to store heap elements
int capacity; // Maximum capacity of the heap
int size; // Current size of the heap
} Heap;
// Function to create a new heap
Heap* createHeap(int capacity)
{
Heap* heap = (Heap*)malloc(sizeof(Heap));
heap->array = (int*)malloc(capacity * sizeof(int));
heap->capacity = capacity;
heap->size = 0;
return heap;
}
// Function to swap two elements in the heap
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Function to heapify a subtree rooted at index i
void heapify(Heap* heap, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
// Check if the left child is larger than the root
if (left < heap->size && heap->array[left] > heap->array[largest])
largest = left;
// Check if the right child is larger than the largest so far
if (right < heap->size && heap->array[right] > heap-
>array[largest])
largest = right;
// If the largest is not the root, swap the root with the largest
if (largest != i) {
swap(&heap->array[i], &heap->array[largest]);
heapify(heap, largest);
}
}
// Function to insert a new element into the heap
Page 4 of 9

void insert(Heap* heap, int value)


{
if (heap->size == heap->capacity) {
printf("Heap is full. Cannot insert more elements.\n");
return;
}
// Insert the new element at the end
int i = heap->size++;
heap->array[i] = value;
// Fix the heap property if it is violated
while (i != 0 && heap->array[(i - 1) / 2] < heap->array[i]) {
swap(&heap->array[i], &heap->array[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
// Function to extract the maximum element from the heap
int extractMax(Heap* heap)
{
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;
}
// Function to print the elements of the heap
void printHeap(Heap* heap)
{
printf("Heap elements: ");
for (int i = 0; i < heap->size; i++) {
printf("%d ", heap->array[i]);
}
printf("\n");
}
// Example usage of the heap
int main()
Page 5 of 9

{
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

Max Heap Deletion Algorithm


Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap always happens at
the root to remove the Maximum (or minimum) value.

Step 1 − Remove root node.


Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.
Page 6 of 9

Example
Following are the implementations of this operation in various programming languages −

C C++ Java Python

Open Compiler

//C code for Max Heap Deletion Algorithm


#include <stdio.h>
#include <stdlib.h>
// Structure to represent a heap
typedef struct {
int* array; // Array to store heap elements
int capacity; // Maximum capacity of the heap
int size; // Current size of the heap
} Heap;
// create a new heap
Heap* createHeap(int capacity)
{
Heap* heap = (Heap*)malloc(sizeof(Heap));
heap->array = (int*)malloc(capacity * sizeof(int));
heap->capacity = capacity;
heap->size = 0;
return heap;
}
// swap two elements in the heap
void swap(int* a, int* b)
{
Page 7 of 9

int temp = *a;


*a = *b;
*b = temp;
}
// Heapify a subtree rooted at index i
void heapify(Heap* heap, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
// Check if the left child is larger than the root
if (left < heap->size && heap->array[left] > heap->array[largest])
largest = left;
// Check if the right child is larger than the largest so far
if (right < heap->size && heap->array[right] > heap-
>array[largest])
largest = right;
// If the largest is not the root, swap the root with the largest
if (largest != i) {
swap(&heap->array[i], &heap->array[largest]);
heapify(heap, largest);
}
}
// Function to insert a new element into the heap
void insert(Heap* heap, int value)
{
if (heap->size == heap->capacity) {
printf("Heap is full. Cannot insert more elements.\n");
return;
}
// Insert the new element at the end
int i = heap->size++;
heap->array[i] = value;
// Fix the heap property if it is violated
while (i != 0 && heap->array[(i - 1) / 2] < heap->array[i]) {
swap(&heap->array[i], &heap->array[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
// delete the maximum element from the heap
int deleteMax(Heap* heap)
{
Page 8 of 9

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

You might also like