A program to to implement Merge Sort.
Initialize two 1-D arrays of 10 and 5 elements, sort them in ascending order, and then merge them into a final array of 15 elements such that the final array also appears in sorted order.

 

#include<iostream.h>
#include<conio.h>

int i,j,a[10],b[5],c[15];

void array1()
{
int temp;
for(i=0;i<9;i++)
{
for(j=0;j<9-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

void array2()
{
int temp;
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
}

void array3()
{
int x=0,y=0,z=0;

while(x<10 && y<5)
{
if(a[x]<b[y])
{
c[z]=a[x];
x++;
}
else
{
c[z]=b[y];
y++;
}
z++;
}

if(x==10)
{
for(i=y;i<5;i++)
{
c[z]=b[i];
z++;
}
}
else
{
for(i=x;i<10;i++)
{
c[z]=a[i];
z++;
}
}
}

void display()
{
cout<<"\nThe first sorted array is:"<<endl;
for(i=0;i<10;i++)
cout<<a[i]<<" ";

cout<<"\n\nThe second sorted array is:"<<endl;
for(i=0;i<5;i++)
cout<<b[i]<<" ";

cout<<"\n\nThe final merged array is:"<<endl;
for(i=0;i<15;i++)
cout<<c[i]<<" ";
}

void main()
{
clrscr();

cout<<"Enter elements of frist array (10 elements):"<<endl;
for(i=0;i<10;i++)
{
cout<<"Enter element no."<<i+1<<": ";
cin>>a[i];
}

cout<<"\nEnter elements of second array (5 elements):"<<endl;
for(i=0;i<5;i++)
{
cout<<"Enter element no."<<i+1<<": ";
cin>>b[i];
}

array1();
array2();

array3();
display();

gotoxy(25,24); cout<<"Press any key to continue......";
getch();
}

 

< Back