# include <stdio.h>
int a[100],j;
main()
{
int n,t,i,z;
clrscr();
printf("\t\t\t\t HEAP SORT\n");
printf("\nEnter the no. of elements:\n");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=n/2;i>=1;i--)
adjust(i,n);
printf("\nInitial heap is...\n");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
printf("\n\nIterations:\n");
for(i=n-1;i>0;i--)
{
t=a[i+1];
a[i+1]=a[1];
a[1]=t;
adjust(1,i);
for(z=1;z<=i;z++)
printf("%d ",a[z]);
printf(" \\ ");
for(z=i+1;z<=n;z++)
printf("%d ",a[z]);
printf("\n");
}
getch();
clrscr();
printf("\nThe sorted elements are...\n");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
}
adjust (i,n)
{
int r,k;
r=a[i];
k=a[i];
j=2*i;
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
j+=1;
if(k>=a[j])
break;
a[j/2]=a[j];
j=2*j;
}
a[j/2]=r;
}
No comments:
Post a Comment