New Android apps UniqueKey

Friday, 20 February 2015

Heap Sort


#include<stdio.h>
#include<stdlib.h>

main()
{
 int heap[50],i,j,ch,size,loc,par;
    int temp;
 
 printf("enter the size of heap tree\n");
 scanf("%d",&size);
 
 printf("all the elements\n");
 for(i=0;i<size;i++)
 scanf("%d",&heap[i]);
 
 for(i=0;i<size;i++)
 {
  loc=i;
  do
  {
   par=(loc-1)/2;
   if(heap[par]<heap[loc])
   {
    temp=heap[par];
    heap[par]=heap[loc];
    heap[loc]=temp;
   }
   loc=par;
  }while(loc!=0);
 }
 printf("heap tree is \n");
 for(i=0;i<size;i++)
 printf("%d\t",heap[i]);
 
 for(j=size-1;j>=0;j--)
 {
  temp=heap[0];
    heap[0]=heap[j];
    heap[j]=temp;
  par=0;
  do
  {
   ch=2*par+1;
   if(heap[ch]<heap[ch+1]&&ch<j-1)
   ch++;
   if(heap[par]<heap[ch]&&ch<j)
   {
    temp=heap[par];
    heap[par]=heap[ch];
    heap[ch]=temp;
   }
   par=ch;
  }while(ch<j);
 }
 printf("\nsorted array\n");
 for(i=0;i<size;i++)
 printf("%d\t",heap[i]);
}

No comments:

Post a Comment