07 June, 2013

C++ Program To Perform Merge Sort.

This Post Contains A C++ Program To Perform Merge Sort With Correct Source Code, Algorithm & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'Merge Sort', 'Array', 'Function', 'Nested Loops' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.


# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.


C++ Program To Perform Merge Sort.

/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>

/* Function Declaration */
void Merge(int c[], int r[]);
/* Start Of Main Program */
void main()
{

/* Declaration Of Variables */
int a[10], b[10], c[20];
int i=0, j=0, x, y;
clrscr();
/* Asking For The Input From User */
cout<<" \n Enter Dimension For Array A : ";
cin>>x;
cout<<" \n Enter "<<x<<" Values For Array A : ";
for(i=0; i<x; i++)
{
   cin>>a[i];
}

cout<<" \n Enter Dimension For Array B : ";
cin>>y;
cout<<" \n Enter "<<y<<" Values For Array B : ";
for(i=0; i<y; i++)
{
   cin>>b[i];
}

/* Source Code For Computing Merge Sort */
for(i=0; i<x; i++)
c[i]=a[i];
while(j<y)
c[i++]=b[j++];
Merge(c,x+y);           // Function Call.
getch();
}
/* End Of Main Program */

/* Function Definition */
void Merge(int c[], int r[])
{

/* Declaration Of Local Variables Of Function */
int k, p, q, fl, fu, sl, su, size, d[20];
size=1;
while(size<r)
{
   fl=0;k=0;
   while(fl+size<r)
   {
      sl=fl+size;
      fu=sl-1;
      su=(sl+size-1<r)?sl+size-1:r-1;
      for(p=fl, q=sl; p<=fu && q<=su; k++)
      {
         if(c[p]<=c[q])
         {
           d[k]=c[p++];
         }
         else
         {
           d[k]=c[q++];
         }
      }
      for(; p<=fu; k++)
      {
         d[k]=c[p++];
      }
      for(; q<=su; k++)
      {
         d[k]=c[q++];
      }
      fl=su+1;
   }
   for(p=fl; k<r; p++)
   {
      d[k++]=c[p];
   }
   for(p=0; p<r; p++)
   {
      c[p]=d[p];
   }
   size*=2;
}
cout<<"\n";
for(q=0; q<r; q++)
   cout<<c[q]<<"\t";
}
/* End Of Function */


Output :

Enter Dimension For Array A : 4
Enter 4 Values For A :
01  2  83  45

Enter Dimension For Array B : 8
Enter 8 Values For B :
65  64  37  82  19  10  25  63

After Merge Sort :
01  10  19  25  29  37  45  63  64  65  82  83




No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.

Blog Archive