#include<stdio.h>
#include<stdlib.h>
void heapsort(int a[20],int n);
void heapify(int a[20],int n);
void adjust(int a[20],int n,int i);
int main()
{
int a[20],i,n;
printf("Enter size of the array: ");
scanf("%d",&n);
printf("Enter elements into the array:\n");
for(i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
heapsort(a,n);
printf("The Sorted Elements are:\n");
for(i=1; i<=n; i++)
{
printf("%d\t",a[i]);
}
}
void heapsort(int a[20],int n)
{
int t,i;
heapify(a,n);
for(i=n; i>=2; i--)
{
t=a[i];
a[i]=a[1];
a[1]=t;
adjust(a,i-1,1);
}
}
void heapify(int a[20],int n)
{
int i;
for(i=n/2; i>=1; i--)
adjust(a,n,i);
}
void adjust(int a[20],int n,int i)
{
int key=a[i],j;
j=2*i;
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
{
j++;
}
if(key<a[j])
{
a[j/2]=a[j];
j=2*j;
}
else
break;
}
a[j/2]=key;
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter size of the array: 5
Enter elements into the array:
8
4
5
3
2
The Sorted Elements are
2 3 4 5 8