C++ Question: Merging two Arrays of different sizes How do i Merge two Arrays of
ID: 668961 • Letter: C
Question
C++ Question: Merging two Arrays of different sizes
How do i Merge two Arrays of different sizes and put it in order in a new array? it has to be in order when its in the new array with out having to sort.
void merge( unsigned combo[], const unsigned a[], unsigned aElements, const unsigned b[], unsigned bElements )
{
}
a is supposed to be sorted, according to the sorted function.
b is supposed to be sorted, according to the sorted function.
The number of elements in the combo array is aElements + bElements. merge’s job is to go through the a and b arrays, copying the elements from a and b into combo in such a way that combo ends up being sorted.
For instance, if a were {3, 5, 7, 7, 9} and b were {2, 5, 8, 1234} (so combo must have 9 elements), then this function will set combo to {2, 3, 5, 5, 7, 7, 8, 9, 1234}. Do this the efficient way: when you put values into combo, always put them in the right location; don’t put the number in haphazardly and rearrange them later.
Explanation / Answer
Mergesort logic will apply to merge the elements from 2 sorted arrays into one sorted array.
The C++ code for merging the lists goes here:
#include <iostream>
using namespace std;
void merge(unsigned combo[], const unsigned a[], unsigned aElements, const unsigned b[], unsigned bElements )
{
int first,second,i,j,k;
first = aElements-1;
second = bElements-1;
i=j=k=0; //i points to first element in a, and j points to first element in b.
while(i <= first && j <= second) //As long as you have elements in both the arrays a and b.
{
if(a[i] < b[j]) //If the element in a is less than that of b
combo[k++] = a[i++]; //Copy the element from array a to combo.
else //If not
combo[k++] = b[j++]; //Copy the element from array b to combo.
}
while(i <= first) //Copy the remaining elements in a to combo(if unempty).
combo[k++] = a[i++];
while(j <= second) //Copy the remaining elements in b to combo(if unemtpy).
combo[k++] = b[j++];
}
int main()
{
const unsigned a[]= {3,5,7,7,9};
const unsigned b[]= {2,5,8,1234};
unsigned combo[50];
merge(combo,a,5,b,4);
for(int i=0;i<9;i++)
cout<<combo[i]<<" ";
}
Ofcourse, you only need the function merge(), and can be reused as per your requirement.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.