Saturday 22 October 2011

Program on Merge Sort


#include<iostream>
#include<cstdlib>
using namespace std;
class array
{
      int a[10],n,b[10];
      public:
             void create(int n);
             void display(int n);
             void sort(int low,int high);
             void mergesort(int low,int mid,int high);

};
void array::create(int n)
{

     cout<<"the elements are:\n";
     for(int i=0;i<n;i++)
     cin>>a[i];
}
void array::display(int n)
{
     for(int i=0;i<n;i++)
     cout<<a[i]<<endl;
}
void array::sort(int low,int high)
{
     if(low<high)
     {
        int mid=(low+high)/2;
        sort(low,mid);
        sort(mid+1,high);
        mergesort(low,mid,high);
     }
}
void array::mergesort(int low,int mid,int high)
{
     int h=low,k=0;
     int i=low;
     int j=mid+1;
     while(h<=mid&&j<=high)
     {
         if(a[h]<a[j])
                b[k++]=a[h++];
         else
                b[k++]=a[j++];
     }
     while(h<=mid)
     {
         b[k++]=a[h++];

     }
       while(j<=high)
            b[k++]=a[j++];
            j=0;
        for(int k=low;k<=high;k++)
        a[k]=b[j++];
}
int main()
{
    array a;
    int n;
    cout<<"the no.of elements in array are:\n";
    cin>>n;
    a.create(n);
    cout<<"the given array is:\n";
    a.display(n);
    int low=0;
    int high=n-1;
    a.sort(low,high);
    cout<<"the sorted array is:\n";
    a.display(n);
    return 0;
}


OUTPUT:-

the no.of elements in array are:
5
the elements are:
1
6
8
2
3
the given array is:
1
6
8
2
3
the sorted array is:
1
2
3
6
8

No comments:

Post a Comment