Wednesday, 20 August 2014

Filled Under:

C Program to Implement Heap Sort

Share

 Heap sort algorithm starts by building a heap from the given elements,and then heap removes its largest element from the end of partially sorted array. After removing the largest element, it reconstructs the heap, removes the largest remaining item, and places it in the next open position from the end of the partially sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Elementary implementations require two arrays - one to hold the heap and the other to hold the sorted elements. 

C Program to Implement Heap Sort 

#include<stdio.h>
#include<conio.h>

int main()
{
      int TREE[10],N,i,j,K,p,c,temp;
      printf("nn Enter no of elements..");
      scanf("%d",&N);
      printf("nn Enter the nos..");
      for(i=1;i<=N;i++)
      scanf("%d",&TREE[i]);
      for(i=2;i<=N;i++)
      {
          K=i;
          do
          {
              if(TREE[K]>TREE[K/2])                          
              {
                  temp=TREE[K];
                  TREE[K]=TREE[K/2];
                  TREE[K/2]=temp;
              }
              p=K/2;
              K=p;
          }
          while(K!=0);
      }
      printf("nnn On inserting values are arranged as n");
      for(i=1;i<=N;i++)                                
      printf("%dt",TREE[i]);
      for(j=N;j>0;j--)
      {
          temp=TREE[1];
          TREE[1]=TREE[j];
          TREE[j]=temp;
          p=0;
          do
          {                                              
               c=2*p+2;
               if((TREE[c][/c]<TREE[c language="+1"][/c]) && c<j-1)
               c++;
               if(TREE[p]<TREE[c][/c] && c<j)
               {
                    temp=TREE[p];
                    TREE[p]=TREE[c][/c];
                    TREE[c][/c]=temp;
               }
           p=c;
           }
           while(c<(j+1));
      }
      printf("nnn The sorted nos are..");
      for(i=1;i<=N;i++)                         
      printf("%dt",TREE[i]);
      getch();
}




Output
Enter size of an array:10
Enter elements of an array:23 43 56 34 12 34 55 65 76 21
After sorting:12 21 23 34 34 43 55 56 65 76