Program to sort given element using Heap Sort in C

/*
   Heap Sort Algorithm
   Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
int a[500],size;
void heap_sort(int a[]);
void build_max_heap(int a[]);
void max_heapify(int a[],int i);
int main()
{
     int i,s;
     printf("** HEAP SORT **");
     printf("\nEnter the No. of elements.\n");
     scanf("%d",&size);
     printf("Enter the %d elements:\n",size);
     for(i=0;i<size;i++)
     scanf("%d",&a[i]);
     size--;
     s=size;
     heap_sort(a);
     printf("********************************");
     printf("\nAfter Sorting\n");
     for(i=0;i<=s;i++)
     printf("%d\t",a[i]);
     getch();
}
void build_max_heap(int a[])
{
     int i;
     for(i=(size)/2;i>=0;i--)
     {
                           max_heapify(a,i);
     }
}
void max_heapify(int a[],int i)
{
     int l,r,temp,largest,j;
     l=i*2+1;
     r=i*2+2;
     if((l<=size) && a[l]>a[i])
     largest=l;
     else
     largest=i;
     if((r<=size) && a[r]>a[largest])
     largest=r;
     if(largest!=i)
     {
                   temp=a[i];
                   a[i]=a[largest];
                   a[largest]=temp;
                   max_heapify(a,largest);
     }
}
void heap_sort(int a[])
{
     int i,t;
     build_max_heap(a);
     for(i=size;i>=0;i--)
     {
                       t = a[0];
                       a[0] = a[i];
                       a[i] = t;
                       size=size-1;   
                       max_heapify(a,0);
     }
}


Output



















0 comments:

Post a Comment

 

Pro

About