In: Computer Science
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 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;
}
Complete program with implementation of SortArrays() function. I have added inline comments also. Do let me know in case of any doubt.
#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=size-1, j=size-1, k=0;
//run loop from the end of array and put the largest number in c array first
while(i>=0 && j>=0){
if(a[i]>b[j])
c[k++] = a[i--];
else
c[k++] = b[j--];
}
//These two loops are to add the remaining elements of either a or b array
while(i>=0){
c[k++] = a[i--];
}
while(j>=0){
c[k++] = b[j--];
}
}
void printArray(int m[], int length) {
for(int i = 0; i < length; i++)
cout<< m[i]<<" ";
cout<<endl;
}
Screenshot:
Output: Resultant array in descending order.