In: Computer Science
in C++
Given two integer arrays sorted in the ascending order, code the function SortArrays to merge them into one array in the descending order. You need to make sure if the values in the arrays are changed, it will still work. (25 points)
#include <iostream>
using namespace std;
void SortArrays (int a[], int b[], int c[], int size);
void printArray(int m[], int length);
const int NUM = 5;
int main()
{
int arrA[NUM] = {-2, 31, 43, 55, 67};
int arrB[NUM] = {-4, 9, 11, 17, 19};
int result[2*NUM];
SortArrays(arrA, arrB, result, NUM);
printArray(result, 2*NUM);
return 0;
}
void SortArrays (int a[], int b[], int c[], int size)
{
}
void printArray(int m[], int length)
{
for(int i = 0; i < length; i++)
cout<< m[i]<<" ";
cout<<endl;
}
The C++ code along with the comments is given below.
#include <iostream>
using namespace std;
void SortArrays (int a[], int b[], int c[], int size);
void printArray(int m[], int length);
const int NUM = 5;
int main()
{
int arrA[NUM] = {-2, 31, 43, 55, 67};
int arrB[NUM] = {-4, 9, 11, 17, 19};
int result[2*NUM];
SortArrays(arrA, arrB, result, NUM);
printArray(result, 2*NUM);
return 0;
}
void SortArrays (int a[], int b[], int c[], int size)
{ int i,j,temp;
//copy array a into array c
for(i=0, j=0; i<size; i++, j++)
{ c[i]=a[j];
}
//copy array b to the end of array c
for(i=size, j=0; i<2*size; i++, j++)
{ c[i]=b[j];
}
//sort the array c in descending order
for(i=0; i<2*size; i++)
{ for(j=i+1; j<2*size; j++)
{
if(c[j]>c[i]) //if c[j]> c[i], then swap the
values to make it in descending order
{ temp=c[j]; //store c[j] to a variable
c[j]=c[i]; //update c[j] with c[i]
c[i]=temp; //update c[i] with value in the temp, now the values are
swapped
}
}
}
}
void printArray(int m[], int length)
{
for(int i = 0; i < length; i++)
cout<<
m[i]<<" ";
cout<<endl;
}
The screenshot of the function snippet is given below.
The output of the code is given below.
Explanation
Hope this helps. Doubts, if any, can be asked in the comment section.