C++ programs for sorting a given numbers in ascending order using Merge sort

/* Write C++ programs for sorting a given list of elements in ascending order using Merge sort methods */

#include<iostream>
#include<conio.h>
using namespace std;
void mergesort(int *,int,int);
void merge(int *,int,int,int);
int a[20],i,n,b[20];
 
main()
{
cout <<"\n enter no of elements";
cin >> n;
cout <<"enter the elements";
for(i=0;i<n;i++)
cin >> a[i];
mergesort(a,0,n-1);
cout <<" numbers after sort";
for(i=0;i<n;i++)
cout << a[i] << " ";
getch();
}
 
void mergesort(int a[],int i,int j)
{
   int mid;
   if(i<j)
   {
      mid=(i+j)/2;
      mergesort(a,i,mid);
      mergesort(a,mid+1,j);
      merge(a,i,mid,j);
   }
}
void merge(int a[],int low,int mid ,int high)
{
   int h,i,j,k;
   h=low;
   i=low;
    j=mid+1;
   while(h<=mid && j<=high)
   {
      if(a[h]<=a[j])
	 b[i]=a[h++];
      else
	 b[i]=a[j++];
      i++;
   }
 
   if( h > mid)
      for(k=j;k<=high;k++)
	b[i++]=a[k];
   else
      for(k=h;k<=mid;k++)
	 b[i++]=a[k];
 
   cout <<"\n";
   for(k=low;k<=high;k++)
   {  a[k]=b[k];
     cout << a[k] <<" ";
   }
 
}

OUTPUT

N enter no of elements8 12 5 61 60 50 1 70 81
enter the elements
5 12
60 61
5 12 60 61
1 50
70 81
1 50 70 81
1 5 12 50 60 61 70 81 numbers after sort1 5 12 50 60 61 70 81


23 Responses to “C++ programs for sorting a given numbers in ascending order using Merge sort”

  1. Christine Huber

    Hello very nice website!! Guy .. Beautiful .. Superb .. I will
    bookmark your site and take the feeds also? I’m glad
    to seek out numerous useful info right here
    within the submit, we need work out more techniques
    in this regard, thanks for sharing. . . . .
    .

    Reply

Leave a Reply