Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Wednesday, 24 January 2018

C program to implement Heap Sort

#include<stdio.h>
main()
{
int i,n,j,root,c,temp;
int a[10];
printf("enter the size of array\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<n;i++)
{

    c=i;
    do
    {

        root=(c-1)/2;
        if(a[root]<a[c])
        {

            temp=a[root];
            a[root]=a[c];
            a[c]=temp;

        }
        c=root;

    }
    while(c!=0);
}
printf("heap array:\t");
for(i=0;i<n;i++)
    printf("%d\t",a[i]);
for(j=n-1;j>=0;j--)
{

    temp=a[0];
    a[0]=a[j];
    a[j]=temp;
    root=0;

    do
    {

        c=2*root+1;
        if((a[root]<a[c+1])&&c<j-1);
        c++;
        if(a[root]<a[c]&&c<j)
        {
        temp=a[root];
    a[root]=a[c];
    a[c]=temp;

        }

    root=c;
    }while(c<j);

}

printf("\tsorted array is:\t");
for(i=0;i<n;i++)
    printf("\t%d",a[i]);
}

No comments:

Post a Comment