Home / C / Program for Heap Sort in C

Program for Heap Sort in C

Program for Heapsort in C that includes functions heapify, maxheap and  buildmaxheap.

#include<stdio.h> //Heapsort program in c
#include<conio.h>
void maxheap(int [],int,int);   //heap sort function containing the heap
void buildmaxheap(int [],int);
void heapsort(int[],int);
int main()
{
 int a[20],i,n;
printf("Enter Total No. of Elements");
 scanf("%d",&n);
 printf("Enter The Elements: \n");
 for (i=1;i<=n;i++)
 scanf("%d", &a[i]);
 heapsort(a,n);
 printf("Sorted Elements Are:\t");
 for(i=1;i<=n;i++)
 {
  printf("%d\t",a[i]);
 }
 return 1;
}
 void maxheap(int a[],int i,int n)
 {
  int r,l,lrg,key;
  l=(2*i);
  r=(2*i)+1;
  if((l<=n)&&(a[l]>a[i]))
  {
  lrg=l;
  }
  else
  {
   lrg=i;
  }
  if ((r<=n)&&(a[r]>a[lrg]))
  {
   lrg=r;
  }
  if(lrg!=i)
	{
   key=a[i];
   a[i]=a[lrg];
   a[lrg]=key;
   maxheap(a,lrg,n);
  }
 }
 void buildmaxheap(int a[],int n)
 {
  int i;
  for(i=(n/2);i>=1;i--)
  {
  maxheap(a,i,n);
  }
 }
 void heapsort(int a[],int n)
 {
  int i, temp;
  buildmaxheap(a,n);
  for(i=n;i>=2;i--)
  {
   temp=a[1];
   a[1]=a[i];
   a[i]=temp;
   maxheap(a,1,i-1);
  }
 }

 

OUTPUT

Heap sort porogram in c
Tags: heapsort program in c, program for heapsort in c, heap sort in c.

Check Also

Restrict Mouse Pointer Position C Graphics Program

This C Program will restrict the Mouse Pointer location or to a particular position or x,y ...

Leave a Reply

Your email address will not be published. Required fields are marked *

Preventing spam * Time limit is exhausted. Please reload the CAPTCHA.