Heap Sort

 #include<iostream.h>  
 #include<conio.h>  
 class heap  
 {  
      public:  
           void heapsort(int a[],int n);  
           void heapify(int a[],int n);  
           void adjust(int a[],int n,int i);  
 };  
 void heap :: heapsort(int a[],int n)  
 {  
      int t;  
      heapify(a,n);  
      for(int i=n;i>=2;i--)  
      {  
            t=a[i];  
            a[i]=a[1];  
            a[1]=t;  
            adjust(a,1,i-1);  
      }  
 }  
 void heap :: heapify(int a[],int n)  
 {  
      for(int i=n/2;i>=1;i--)  
           adjust(a,i,n);  
 }  
 void heap :: adjust(int a[],int i,int n)  
 {  
      int item, j;  
      j=2*i;  
      item=a[i];  
      while(j<=n)  
      {  
           if((j<n)&&(a[j]<a[j+1]))  
                  j=j+1;  
           if(item>=a[j])  
                break;  
           a[j/2]=a[j];  
           j=2*j;  
      }  
      a[j/2]=item;  
 }  
 void main()  
 {  
      int a[10],n,j,i;  
      heap h;  
      clrscr();  
      cout<<endl<<"Enter the array size: ";  
      cin>>n;  
      cout<<endl<<"Enter the elements : ";  
      for(i=1;i<=n;i++)  
           cin>>a[i];  
      h.heapsort(a,n);  
      cout<<endl<<endl<<"SORTED ARRAY"<<endl;  
      for(i=1;i<=n;i++)  
           cout<<'\t'<<a[i];  
      getch();  
 }  

Share This!


No comments:

Post a Comment

Code Of The day - Suggest An Output For The Snippet

  #include<stdio.h>   
  int main()   
  {   
   float a=3.15529;   
   printf("%2.1f\n", a);   
   return 0;   
  }   
· A Code Archive - code1archive