Here is a simple program of heapsorting in c language:
#include<stdio.h>
void create();
void sort();
void display();
int list[10];
int n=10;
void create()
{
int k,j,i,temp;
int n=10;
for(k=2;k<=n;k++)
{
i=k;
temp=list[k];
j=i/2;
while((i>1)&&(temp>list[j]))
{
list[i]=list[j];
i=j;
j=i/2;
if(j<1)
j=1;
}
list[i]=temp;
}
}
void sort()
{
int k,temp,value,j,i;
int n=10;
for(k=n;k>=2;k–)
{
temp=list[1];
list[1]=list[k];
list[k]=temp;
i=1;
value=list[1];
j=2;
if(j+1<k)
if(list[j+1]>list[j])
j++;
while((j<=(k-1)&&list[j]>value))
{
list[i]=list[j];
i=j;
j=2*i;
if((j+1)<k)
if(list[j+1]>list[j])
j++;
else
if(j>n)
j=n;
list[i]=value;
}
}
}
void display()
{
int i;
for(i=1;i<=10;i++)
printf(“%d “,list[i]);
}
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf(“Enter a value: “);
scanf(“%d”,&list[i]);
}
printf(“\nThe entered list is as follows:\n”);
display();
create();
printf(“\nThe heap is as follows:\n”);
display();
sort();
printf(“\nSorted list is as follows:\n”);
display();
getch();
}
Advertisements