C++ Program Code for Merge Sort Algorithm implementation on an array, using template class

Leave a Comment
/*The following C++ Program code is to implement merge sort algorithm of array sorting. The user is asked first to enter the number of element in the array & then he also enters the elements in that array. The merge sorting algorithm is applied on that array & the sorted array is displayed */

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T>
void m_sort(T nos[],T t[],int l,int r);


template<class T>
void mergesort(T nos[],T t[],int asize)
{
     m_sort<T>(nos,t,0,asize-1);
}


template<class T>
void m_sort(T nos[],T t[],int l,int r)
{
     int mid;
     if(r>l)
     {
                   mid=(r+l)/2;
                   m_sort(nos,t,l,mid);
                   m_sort(nos,t,mid+1,r);
                   merge(nos,t,l,mid+1,r);
     }
}


template<class T>
void merge(T nos[],T t[],int l,int mid,int r)
{
     int i,l_end,num_elements,t_pos;
         l_end=mid-1;
         t_pos=l;
         num_elements=r-l+1;
         while((l<=l_end)&&(mid<=r))
         {
                                              if(nos[l]<=nos[mid])//(kept -nos instead )
                                              {
                                                                              t[t_pos]=nos[l];
                                                                              t_pos++;
                                                                              l++;
                                              }
                                              else
                                              {
                                                                              t[t_pos]=nos[mid];
                                                                              t_pos++;
                                                                              mid++;
                                              }
         }
         while(l<=l_end)
         {
                               t[t_pos]=nos[l];
                               l++;
                               t_pos++;
         }
         while(mid<=r)
         {
                          t[t_pos]=nos[mid];
                          mid++;
                          t_pos++;
         }
         for(i=0;i<=num_elements;i++)
         {
                                     nos[r]=t[r];
                                     r--;
         }
}


int main()
{
    int a[20],b[20],n;
    cout<<"\nEnter The Total Number Of Elements:";
    cin>>n;
    cout<<"\nEnter "<<n<<" elements (Use Spacebar as separator) : ";
    for(int i=0;i<n;i++)
    {
                    cin>>a[i];
    } 

    mergesort(a,b,n);

    cout<<"\nThe sorted element list is \n";
    for(int i=0;i<n;i++)
    {
                    cout<<a[i]<<"\t";
    }

    system("pause");
    return 0;
}


Screenshot:
C++ Program Code for Merge Sort Algorithm implementation on an array, using template class

0 comments: