HEAP SORT


SOURCE CODE:

“Heap.h” File:

#include<stdio.h>
#include<conio.h>
#define leftchild(i) (2*i+1)

void swap(int *x,int *y)
{
   int temp;
   temp=*x;
   *x=*y;
   *y=temp;
}
void percdown(int A[],int i,int n)
{
   int child,tmp;
   for(tmp=A[i];leftchild(i)<n;i=child)
   {
     child=leftchild(i);
     if(child!=n-1&&A[child+1]>A[child])
    child++;
     if(tmp<A[child])
    A[i]=A[child];
     else
    break;
   }
   A[i]=tmp;
}
void display(int A[],int n)
{
   int i;
   for(i=0;i<n;i++)
   {
     printf("\t%d\t",A[i]);
   }
   printf("\n");
}
void heapsort(int A[],int n)
{
   int i;
   for(i=n/2;i>=0;i--)
     percdown(A,i,n);
   display(A,n);
   for(i=n-1;i>0;i--)
   {
     swap(&A[0],&A[i]);
     percdown(A,0,i);
     display(A,n);
     getch();
   }
}


“Heap.c” File:

#include"heap.h"
void main()
{
int A[20],n;
int i;
clrscr();
printf("\n\n How many numbers do u want to sort:\t");
scanf("%d",&n);
printf("\n Enter the values");
for(i=0;i<n;i++)
{
   printf("\nA[%d]\t",i);
   scanf("%d",&A[i]);
}
heapsort(A,n);
getch();
}

OUTPUT:

 How many numbers do u want to sort:   5
 Enter the values
A[0]    100
A[1]    25
A[2]    10
A[3]    9
A[4]    5
        
      100             25              10              9               5
        25              9               10              5               100
        10              9               5               25              100
        9               5               10              25              100
        5               9               10              25              100
Previous
Next Post »

Still not found what you are looking for? Try again here.