You are on page 1of 2

HEAP SORT

#include<stdio.h>
void maxheapify(int a[],int ,int);
void heapsort(int a[],int);
int main()
{
int n,arr[100],i;
printf("enter the size");
scanf("%d",&n);
printf("enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
heapsort(arr,n);
printf(" sorted elements are");
for(i=0;i<n;i++)
printf("\t%d",arr[i]);
}
void maxheapify(int a[],int n,int i)
{
int temp,largest=i;
int l=(2*i)+1;
int r=(2*i)+2;
if(l<=n&&a[l]>a[largest])
largest=l;
if(r<=n&&a[r]>a[largest])
largest=r;
if(largest!=i)
{
temp=a[largest];
a[largest]=a[i];
a[i]=temp;
maxheapify(a,n,largest);
}
}
void heapsort(int a[],int n)
{
int kemp,i;
for(i=n/2-1;i>=0;i--)
maxheapify(a,n,i);
for(i=n-1;i>=0;i--)
{
kemp=a[0];
a[0]=a[i];
a[i]=kemp;
maxheapify(a,i-1,0);
}
}

You might also like