MERGE SORT
Write a C++ program to accept two single dimensional
arrays, A in ascending order and B in descending order and Merge them into
array C in ascending order.
#include<iostream.h>
void
merge(int[],int,int[],int,int[]);
void main()
{
int
A[50],B[50],C[50],MN=0,M,N;
cout<<"How many
elements do u want to create first array with ?";
cin>>M;
cout<<"\nEnter
first array elements [ascending]..\n";
for(int i=0;i<M;i++)
cin>>A[i];
cout<<"\nHow many
elements you want to create second array with?";
cin>>N;
MN=M+N;
cout<<"\nEnter
second array elements[decending]";
for(i=0;i<N;i++)
cin>>B[i];
merge(A,M,B,N,C);
cout<<"\n\nThe
merged array is as shown below..\n";
for(i=0;i<MN;i++)
cout<<C[i];
cout<<endl;
}
void merge(int A[],int M,int
B[],int N,int C[])
{
int a,b,c;
for(a=0,b=N-1,c=0;a<M
&& b>=0;)
{
if(A[a] <= B[b])
C[c++] = A[a++];
else
C[c++] = B[b--];
}
if(a<M)
{
while(a<M)
C[c++] = A[a++];
}
else
{
while(b>=0)
C[c++] = B[b--];
}
}
No comments:
Post a Comment