Heap sort program in c program - heap sort in data structures
Aim: To sort elements by heap order( max heap) in C program
program:
#include<stdio.h>
void main()
{
int n,a[50],i;
clrscr();
printf("enter elements to be entered");
scanf("%d",&n); printf("enter elements");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("after sorting the elements are");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
}
int heapsort(int a[],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,1,i-1);
}
return;
}
int heapify(int a[],int n)
{
int i; for(i=n/2;i>=1;i--)
adjust(a,i,n);
return;
}
int adjust(int a[],int i,int n)
{
int j,item,t;
j=2*i; item=a[i];
while(j<=n)
{
if(j<n && a[j]<a[j+1])
j=j+1;
if(item<=a[j])
{
t=a[j/2];
a[j/2]=a[j];
a[j]=t;
}
j=2*j;
}
}
Output:
No comments:
Post a Comment