Google Ads

Monday, May 25, 2009

HEAP SORT

#include “stdio.h”
#include “conio.h”
int i,j,a[20],n,q,key,temp;
void heap(int a[20],int n);
void main()
{
clrscr();
printf("\n\t\t\tHEAP SORT");
printf("\n\t\t\t----------------");
printf("\nEnter the no. of elements : ");
scanf("%d",&n);
printf("\nEnter the elements : ");
for(i=0;i scanf("%d",&a[i]);
heap(a,n);
printf("\n Sorted List are:\n");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
}
void createheap(int a[],int n)
{
for(q=1;q {
i=q;
key=a[q];
j=i/2;
while((i>0)&&(key>a[j]))
{
a[i]=a[j];
i=j;
j=i/2;
if(j<0)
j=0;
}
a[i]=key;
}
}
void heap(int a[],int n)
{
createheap(a,n);
for(q=n;q>=1;q--)
{
temp=a[0];
a[0]=a[q];
a[q]=temp;
i=0;
key=a[0];
j=1;
if((j+1) {
if(a[j+1]>a[j])
j++;
}
while((j<=(q-1))&&(a[j]>key))
{
a[i]=a[j];
i=j;
j=2*i;
if((j+1) {
if(a[j+1]>a[j])
j++;
}
else if(j>n-1)
j=n-1;
a[i]=key;
}
}
}


Output will be

Enter the no. of elements : 3

Enter the elements :
12
94
85

Sorted List are:
12 85 94

No comments:

Post a Comment