Sunday, January 26, 2014

C Program to Perform HeapSort

with 0 Comment
C Program to Perform HeapSort:

#include<stdio.h>
#include<conio.h>
void adjust(int b[],int i,int n)
{
int child,tmp;
for(tmp=b[i];i*2<=n;i=child)
{
child=i*2;
if(child!=n&&b[child+1]>b[child])
child++;
if(tmp<b[child])
b[i]=b[child];
else
break;
}
b[i]=tmp;
}
void heap(int b[],int n)
{
int i,t;
for(i=n/2;i>0;i--)
adjust(b,i,n);
for(i=n;i>0;i--)
{
t=b[i];
b[i]=b[1];
b[1]=t ;
adjust(b,1,i-1);
}}

void main()
{
int i,a[50],n;
clrscr();
printf("Heapsort\nEnter the no. of elements to be sorted\n");
scanf("%d",&n);
printf("Enter elements one by one\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
heap(a,n);
printf("Sorted array is:\n");
for(i=1;i<=n;i++)
printf("%d\n",a[i]);
getch();
}

0 comments:

Post a Comment

Powered by Blogger.

Blog Archive