Sunday, 2 September 2012

Merge Sort


#include<iostream.h>
#include<conio.h>

class mergesort
{
private:
    int a[10],temp[10],i,j,k,n,size,l1,h1,l2,h2;
public:
    void read();
    void sort();
    void show();
};

void mergesort::read()
{
    cout<<"Enter how many elements you want to sort : ";
    cin>>n;
    cout<<"Enter "<<n<<" elements to sort : ";
    for(int i=0;i<n;i++)
        cin>>a[i];
}

void mergesort::sort()
{
    for(size=1;size<n;size=size*2)
    {
      l1=0;
      k=0;
      while(l1+size<n)
      {
         h1=l1+size-1;
         l2=h1+1;
         h2=l2+size-1;
         if(h2>=n)
        h2=n-1;
         i=l1;
         j=l2;
         while(i<=h1&&j<=h2)
         {
           if(a[i]<=a[j])
         temp[k++]=a[i++];
        else
         temp[k++]=a[j++];
         }
         while(i<=h1)
        temp[k++]=a[i++];
         while(j<=h2)
        temp[k++]=a[j++];
         l1=h2+1;
         }
         for(i=l1;k<n;i++)
        temp[k++]=a[i];
         for(i=0;i<n;i++)
        a[i]=temp[i];

      }
 }
void mergesort::show()
{
    cout<<"Sorted elements are : ";
    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";
}

void main()
{
    clrscr();
    mergesort m;
    m.read();
    m.sort();
    m.show();
    getch();
}

No comments:

Post a Comment