C Program For Heap Sort | C Programming


A heap is a complete tree with an ordering-relation R holding between each node and its descendant. Note that the complete tree here means tree can miss only rightmost part of the bottom level. R can be smaller-than, bigger-than. E.g. Heap with degree 2 and R is “bigger than”.


Heap Sort 

Build a heap from the given set (O(n)) time, then repeatedly remove the elements from the heap (O(n log n)). Implementation Heaps are implemented by using arrays. Insertion and deletion of an element takes O(log n) time. More on this later

Heap Sort

Heap Sort Pseudo Code

Heapsort(A) {
   for i <- length(A) downto 2 {
      exchange A[1] <-> A[i]
      heapsize <- heapsize -1
      Heapify(A, 1)
BuildHeap(A) {
   heapsize <- length(A)
   for i <- floor( length/2 ) downto 1
      Heapify(A, i)
Heapify(A, i) {
   le <- left(i)
   ri <- right(i)
   if (le<=heapsize) and (A[le]>A[i])
      largest <- le
      largest <- i 
   if (ri<=heapsize) and (A[ri]>A[largest])
      largest <- ri
   if (largest != i) {
      exchange A[i] <-> A[largest]
      Heapify(A, largest)

C Program For Heap Sort By Generating Random Numbers

#include <conio.h>
#include <time.h>
void Adjust(int Heap_of_Numbers[],int i)  /*Function to arrange the elements in the heap*/
    int j;
    int copy;
    int Number;
    int Reference = 1;
    while(2*i<=Number && Reference==1)
        if(j+1<=Number && Heap_of_Numbers[j+1] > Heap_of_Numbers[j])
            if( Heap_of_Numbers[j] < Heap_of_Numbers[i])
void Make_Heap(int heap[])
    int i;
    int Number_of_Elements;

int main()
    int heap[1000];
    int NumberofElements;
    int i;
    int LastElement;
    int CopyVariable;
    time_t t;
    printf("Enter the max number \n");
    srand((unsigned) time(&t));
    printf("\n\nTime taken to complete the heapsort %u\n",clock()/CLOCKS_PER_SEC);
    while(heap[0] > 1) /*Loop for the Sorting process*/
    printf("\nSorted Array:\n");/*Printing the sorted Array*/
        printf("%d ",heap[i]);
    return 0;

Post a Comment