Heap Sort program in C Language

Heap Sort program in C Language algorithm implementation – Heap sort is two types first is min heap and second is max heap processes the elements by creating the min heap or max heap using the elements of the given array. Min heap or max heap represents the ordering of the array in which root element represents the minimum or maximum element of the array.

Complexity

  • Best Case : Time Complexity Ω(n log (n))
  • Average Case: Time Complexity θ(n log (n))
  • Worst case: Time Complexity O(n log (n))
  • Space Complexity O(1)


In this program user would be asked to enter the number of elements along with the element values and then the programs would sort them in ascending order by using merge sorting algorithm logic.

Types of Sorting Algorithms:

<img width=

Heap Sort algorithm C Program implementation

#include<stdio.h>  
int temp;  
  
void heapify(int arr[], int size, int i)  
{  
int largest = i;    
int left = 2*i + 1;    
int right = 2*i + 2;    
  
if (left < size && arr[left] >arr[largest])  
largest = left;  
  
if (right < size && arr[right] > arr[largest])  
largest = right;  
  
if (largest != i)  
{  
temp = arr[i];  
    arr[i]= arr[largest];   
    arr[largest] = temp;  
heapify(arr, size, largest);  
}  
}  
  
void heapSort(int arr[], int size)  
{  
int i;  
for (i = size / 2 - 1; i >= 0; i--)  
heapify(arr, size, i);  
for (i=size-1; i>=0; i--)  
{  
temp = arr[0];  
    arr[0]= arr[i];   
    arr[i] = temp;  
heapify(arr, i, 0);  
}  
}  
  
void main()  
{  
int arr[] = {2, 11, 3, 4, 5, 2, 3, 101,24, 3};  
int i;  
int size = sizeof(arr)/sizeof(arr[0]);  
  
heapSort(arr, size);  
  
printf("printing sorted elements here\n");  
for (i=0; i<size; ++i)  
printf("%d\n",arr[i]);  
}  

OUTPUT



printing sorted elements here

2
2
3
3
3
4
5
11
24
101


Additional Reading

you can read more articles like this here.

READ MORE

If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.❤

Leave a Reply