MergeSort

 #include<iostream.h>  
 #include<conio.h>  
 class merge  
 {  
      private:  
           int n,a[20],b[20];  
      public:  
           void get();  
           void sort(int,int,int);  
           void msort(int,int);  
           void disp();  
 };  
 void merge::get()  
 {  
      cout<<"Enter the limit :";  
      cin>>n;  
      cout<<"\nEnter the elements :";  
      for(int i=0;i<n;i++)  
           cin>>a[i];  
      msort(0,n-1);  
 }  
 void merge::msort(int low,int high)  
 {  
      if(low<high)  
      {  
           int mid=(low+high)/2;  
           msort(low,mid);  
           msort(mid+1,high);  
           sort(low,mid,high);  
      }  
 }  
 void merge::sort(int l,int m,int h)  
 {  
      int low=l;  
      int k;  
      int i=l;  
      int j=m+1;  
      while((low<=m)&&(j<=h))  
      {  
           if(a[low]<=a[j])  
                b[i++]=a[low++];  
           else  
                b[i++]=a[j++];  
      }  
      if(low>m)  
      {  
           for(k=j;k<=h;k++)  
                b[i++]=a[k];  
      }  
      else  
      {  
           for(k=low;k<=m;k++)  
                b[i++]=a[k];  
      }  
      for(k=0;k<=h;k++)  
           a[k]=b[k];  
 }  
 void merge :: disp()  
 {  
      cout<<"\nSORTED ARRAY \n";  
       for(int z=0;z<n;z++)  
           cout<<'\t'<<a[z];  
 }  
 void main()  
 {  
      merge m;  
      clrscr();  
      m.get();  
      m.disp();  
      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