Tuesday, 21 October 2014

C++ program to implement merge sort

C++ program to sort list of numbers using merge sort algorithm.

C++ program to implement merge sort

#include<iostream>
using namespace std;
class sort_list
{
    int data[20];
    int n;
public:
    void get_data();
    void merge_sort(int,int);
    void combine(int,int,int);
    void display();
    int get_n()
    {
        return n;
    }
};
void sort_list::get_data()
{
    cout<<"How many elements two be entered ";
    cin>>n;
    cout<<"Enter the elements ";
    for(int i=0;i<n;i++)
        cin>>data[i];
}
void sort_list::merge_sort(int first,int last)
{
    if(first>=last)
        return;
    int mid=(first+last)/2;
    merge_sort(first,mid);
    merge_sort(mid+1,last);
    combine(first,mid,last);
}
void sort_list::combine(int f,int m,int l){
  int temp[20],i=f,j=m+1,k=f;
  while(i<=m&&j<=l){
      if(data[i]<data[j])
        temp[k++]=data[i++];
      else
        temp[k++]=data[j++];
  }
  while(j<=l)
      temp[k++]=data[j++];
  while(i<=m)
      temp[k++]=data[i++];
  for(i=f;i<=l;i++)
    data[i]=temp[i];
}

void sort_list::display()
{
    cout<<"Sorted list : ";
    for(int i=0;i<n;i++)
        cout<<data[i]<<" ";
}
int main()
{
    sort_list sort;
    sort.get_data();
    sort.merge_sort(0,sort.get_n()-1);
    sort.display();
    return 0;
}

No comments:

Post a Comment