CPPForSchool.com: Array - Single Dimension Set 1 Assignment 9
9.
Suppose X. Y, Z are arrays of integers of size M, N, and M + N
respectively. The numbers in array X and Y appear in descending order.
Write a user-defined function in C++ to produce third array Z by merging
arrays X and Y in descending order.
For this assignment, I had a lot of trouble setting the algorithms up correctly. It seemed like every step forward resulted in additional problems. I eventually had to throw in the towel because I was at a complete loss. Nevertheless, after reviewing the sample source, I began to truly understand my shortcomings and how to handle this sort of task in the future.
-------------------------------------------------------------------------------------------------------------------------
Sample Source Code
-------------------------
For this assignment, I had a lot of trouble setting the algorithms up correctly. It seemed like every step forward resulted in additional problems. I eventually had to throw in the towel because I was at a complete loss. Nevertheless, after reviewing the sample source, I began to truly understand my shortcomings and how to handle this sort of task in the future.
-------------------------------------------------------------------------------------------------------------------------
Sample Source Code
-------------------------
#include<iostream>
using namespace std;
void Merge(int A[], int B[], int C[], int N, int M, int &K);
int main()
{
int A[100], B[100], C[200],i,n,m,k;
cout<<"\nEnter number of elements you want to insert in first array ";
cin>>n;
cout<<"Enter element in descending order\n";
for(i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>A[i];
}
cout<<"\nEnter number of elements you want to insert in second array ";
cin>>m;
cout<<"Enter element in descending order\n";
for(i=0;i<m;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>B[i];
}
Merge(A,B,C,n,m,k);
cout<<"\nThe Merged Array in Descending Order"<<endl;
for(i=0;i<k;i++)
{
cout<<C[i]<<" ";
}
return 0;
}
void Merge(int A[], int B[], int C[], int N, int M, int &K)
{
int I=0, J=0;
K=0;
while (I<N && J<M)
{
if (A[I]>B[J])
C[K++]=A[I++];
else if (A[I]<B[J])
C[K++]=B[J++];
else
{
C[K++]=A[I++];
J++;
}
}
for (int T=I;T<N;T++)
C[K++]=A[T];
for (int T=J;T<M;T++)
C[K++]=B[T];
}
Comments
Post a Comment