Thursday , September 21 2017
Home / C / c program for implementing Heap sort in C Language

c program for implementing Heap sort in C Language

This program is for Heap Sort in C.

#include<stdio.h>
#include<conio.h>
void maxheap(int [],int,int);     //program for implementing heap sort in c
void buildmaxheap(int a[],int n)
{
int i;
for(i=n/2;i>=1;i--)
{
maxheap(a,i,n);
}
}
void maxheap(int a[],int i,int n)
{
int R,L,largest,t;
L=2*i;

R=2*i+1;
if((L<=n) && (a[L]>a[i]))
largest=L;
else
largest=i;
if((R<=n) && (a[i]>a[largest]))
largest=R;
if(largest!=i)
{
t=a[i];
a[i]=a[largest];
a[largest]=t;
maxheap(a,largest,n);
}
}
void heapsort(int a[],int n)
{
int i,temp;
buildmaxheap(a,n);
for(i=n;i>=2;i--)
{
temp=a[1];
a[1]=a[i];
a[i]=temp;
maxheap(a,1,i-1);
}
}
void main()
{
int a[50],i,n;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter the elements of array \n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
heapsort(a,n);
printf("sorted array is \n");
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Incoming terms: Program for implementing heap sort in c, heap sort program in c

Check Also

How to Solve Linear Equation in One Variable In C Programming?

C Program to Solve any Linear Equation in One Variable Find complete C program to ...

4 comments

  1. Enter the size of array : 6
    Enter the elements of array
    3 6 7 8 1 4
    sorted array is
    1 7 3 4 6 8

    The code seems to be messing up , please correct it

  2. correct the max heap function to:

    void maxheap(int a[],int i,int n)
    {
    int R,L,largest,t;
    L=2*i;

    R=2*i+1;
    if((La[i]))
    largest=L;
    else
    largest=i;
    if((Ra[largest]))
    largest=R;
    if(largest!=i)
    {
    t=a[i];
    a[i]=a[largest];
    a[largest]=t;
    maxheap(a,largest,n);
    }
    }

    • void maxheap(int a[],int i,int n)
      {
      int R,L,largest,t;
      L=2*i;

      R=2*i+1;
      if((La[i]))
      largest=L;
      else
      largest=i;
      if((Ra[largest]))
      largest=R;
      if(largest!=i)
      {
      t=a[i];
      a[i]=a[largest];
      a[largest]=t;
      maxheap(a,largest,n);
      }
      }

    • you have not followed the indentation,follow the indentation for batter understanding.

Leave a Reply

Your email address will not be published. Required fields are marked *