Wednesday, 4 September 2013

HEAP SORT C PROGRAM


/*CSEMATTER.BLOGSPOT.IN
Program:C program to implement heap sort*/

#include<stdio.h>
#include<conio.h>
void heapsort(int[],int);
void maxheap(int[],int);
void heapify(int[],int);
void main()
{
 int n,i,a[50];
 printf("Enter the no. to be input:\n");
 scanf("%d",&n);
 printf("Enter the elements:\n");
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 heapsort(a,n);
 printf("\nThe Sorted Elements Are:");
 for(i=0;i<n;i++)
  printf("\t%d",a[i]);
 getch();
}
void heapsort(int a[],int n)
{
 int i,t;
 maxheap(a,n);
 for(i=n-1;i>0;i--)
 {
  t = a[0];
  a[0] = a[i];
  a[i] = t;
  heapify(a,i);
 }
}
void maxheap(int a[],int n)
{
 int k,i,j,item;
 for(k=1;k<n;k++)
 {
  item = a[k];
  i = k;
  j = (i-1)/2;
 while((i>0)&&(item>a[j]))
  {
   a[i] = a[j];
   i = j;
   j = (i-1)/2;
  }
  a[i] = item;
 }
}

void heapify(int a[],int n)
{
 int i,j,item;

 j = 0;
 item = a[j];
 i = 2*j+1;

 while(i<=n-1)
 {
  if(i+1 <= n-1)
   if(a[i] <a[i+1])
    i++;
  if(item<a[i])
  {
   a[j] = a[i];
   j = i;
   i = 2*j+1;
  }
  else
   break;
 }
 a[j] = item;
}
/*Output
Enter the no. to be input: 5
Enter the elements:
12 34 7 9 22
The Sorted Elements Are:
7 9 12 22 34*/

No comments:

Post a Comment