InterviewSolution
| 1. |
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. |
|
Answer» #include <iostream.h> void Merge(int X[],int M,int Y[],int N,int Z[]); int main() { int X[50],Y[50],Z[50],MN=0,M,N; cout<<"How many elements do U want to create first array with? "; cin>>M; cout<<"Enter First Array's elements [descending]..."; for(int i=0;i>X[i]; cout<<"How many elements do U want to create second array with? "; cin>>N; MN=M+N; cout<<"Enter Second Array's elements [descending]..."; for(int i=0;i>Y[i]; Merge(X,M,Y,N,Z); cout<<"The merged array is...."; for(i=0;i<MN;i++) cout<<Y[i]<<" "; cout<<end1; return 0; } void Merge(int X[],int M,int Y[],int N,int Z[]) { int x,y,z; for(x=-1,y=-1,z=-1;x>=0&&y>=0;) { if(X[x]<=Y[y]) Z[z--]=X[x--]; else Z[z--]=Y[y--]; } if(x<0) { while(x>=0) Z[z--]=X[x--]; } else { while(y>=0) Z[z--]=Y[y--]; } } |
|