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

by Nideesh C on April 14, 2011 · 0 comments

in C++




#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



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C++ rogram to implement merge sort
  2. C program to accept N numbers sorted in ascending order and to search for a given number using binary search. Report success or failure in the form of suitable messages
  3. C program to sort N numbers in ascending order array with suitable headings
  4. C program to accept a amtric of order MxN and sort all rows of the matrix in ascending order and all columns in descendng order
  5. This program accepts an array of N elements and a key. Then it searches for the desired element. If the search is successful, it displays “SUCCESSFUL SEARCH”. Otherwise, a message “UNSUCCESSFUL SEARCH” is displayed.

Leave a Comment

Previous post:

Next post: