Here you will get program for heap sort in C.
It is a comparison based sorting technique which uses binary heap data structure.
Below I have shared simple program to implement this sorting technique in C.
Program for Heap Sort in C
void create(int );
void down_adjust(int ,int);
printf("Enter no. of elements:");
//create a heap
while(heap > 1)
//swap heap and heap[last]
//print sorted data
printf("\nArray after sorting:\n");
void create(int heap)
n=heap; //no. of elements
void down_adjust(int heap,int i)
while(2*i<=n && flag==1)
j=2*i; //j points to left child
if(j+1<=n && heap[j+1] > heap[j])
if(heap[i] > heap[j])
Enter no. of elements:5
Enter elements:12 8 46 23 7
Array after sorting:
7 8 12 23 46
9 thoughts on “Program for Heap Sort in C”
why not just a simple bubblesort?
The time complexity of heap sort is O(nlogn) which is better than that of bubble sort which is O(n^2).
I used this program but if I put number of elements in the array greater than 71, some printf lines and elements do not appear in console. Also the more I increase the size of the array the less lines and elements appear in console while the program is running.. What is going on? Does this code have a limit as to how many elements you can use?
You can scroll up to see upper output.
That’s the thing. I scroll way up at the beginning and I notice that a) some printf lines are not printed in console and b) when the sorting ends, not all elements are shown in console, even though if I “fprintf” them into a data.dat I can see all the elements.
I think I know the problem. Because I use 10000 elements or more, the cmd window cant print so many lines it has a 9999 limit and you have to set that too by yourself. the default is like 100 or something. That’s why some of my printf lines magically dissapeared. There was not enough space for them to be printed out in the cmd window.
why do we use down_adjust(heap,1);?
Dwnadjst is actually the sink fuction,the input we gave taken is unsortedbso wif parent<child value parent has to move dwn (Sink) and the child tets promoted that is why we perfem sink,arter one sink we get the highet elem at a
Why n =heap???