C:Program:Implementation of Heap Sort



PROGRAM:

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

//Heap by Vikas KONAPARTHI
#include <stdio.h>
void heap(int a[10],int size);
void heap_adjust(int m,int i,int a[10]);
void ReadArray(int a[10],int size);
void WriteArray(int a[10],int size);

void ReadArray(int a[10],int size)
{
    int i;
    printf("\n Enter %d elements",size);
    for(i=0;i<size;i++)
    scanf("%d",&a[i]);
}
void WriteArray(int a[10],int size)
{
    int i;
    printf("\n Sorted Array\n");
    for(i=0;i<size;i++)
    {
        printf("%d\t",a[i]);
    }   
}
void heap(int a[10],int size)
{
  int i,t;
  for(i=size/2-1;i>=0;i--)
  heap_adjust(size,i,a);
  for(i=size-1;i>=0;i--)
  {
      t=a[0];
      a[0]=a[i];
      a[i]=t;
      heap_adjust(i,0,a);
  }
}
void heap_adjust(int m,int i,int a[10])
{
    int large,right,left,t;
    large =i;
    left=2*i+1;
    right=2*i+2;
    if(left<m && a[left]>a[large])
    large=left;
    if(right<m && a[right]>a[large])
    large=right;
    if(large!=i)
    {
        t=a[i];
        a[i]=a[large];
        a[large]=t;
        heap_adjust(m,large,a);
    }
}
    
void main()
{
    int a[10],size;
    printf("\nEnter the size of array");
    scanf("%d",&size);
    ReadArray(a,size);
    heap(a,size);
    WriteArray(a,size);
}  

Previous Post Next Post