CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER'
QUESTION
Using C++
11. Write a function that will merge the contents of two sorted (ascending order) arrays of type double values, storing the result in an array out- put parameter (still in ascending order). The function shouldn’t assume that both its input parameter arrays are the same length but can assume
First array
04
Second array
Result array
that one array doesn’t contain two copies of the same value. The result array should also contain no duplicate values.
(Hint: When one of the input arrays has been exhausted, don’t forget to copy the remaining data in the other array into the result array.) Test your function with cases in which (1) the first array is exhausted first, (2) the second array is exhausted first, and (3) the two arrays are exhausted at the same time (that is, they end with the same value). Remember that the arrays input to this function must already be sorted.
CODE THAT NEED TO BE WRITTEN IN A DIFFERENT WAY
#include <iostream>
using namespace std;
//Function to merge 2 sorted arrays
int * merge(int *a1, int n1, int *a2, int n2){
//Initialize array to store merged array
static int ans[100];
int i1=0,i2=0,ind=0;
//Loop through both arrays
while(i1<n1&&i2<n2){
//Add minimum element to the array
if(a1[i1]<a2[i2]){
ans[ind++] = a1[i1++];
}
else{
ans[ind++] = a2[i2++];
}
}
//Add remaining elements to the array
while(i1<n1){
ans[ind++] = a1[i1++];
}
while(i2<n2){
ans[ind++] = a2[i2++];
}
return ans;
}
int main()
{
int a1[] = {1,3,5,8};
int a2[] = {2,4,6,7,9,10};
int *ans = merge(a1,4,a2,6);
for(int i=0;i<10;i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}
Modified program:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int * merge(int *a1, int n1, int *a2, int n2){
int* a3 = new int[n1+n2];
a3 = a1; // assign starting address to a1
a2 = a3+n1; // assign address of n1th element to staring address to
a2
sort(a3, a3+n1+n2);
return a3;
}
int main()
{
int a1[] = {1,3,5,8};
int a2[] = {2,4,6,7,9,10};
int *ans = merge(a1,4,a2,6);
for(int i=0;i<10;i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}
output:
Get Answers For Free
Most questions answered within 1 hours.