What is an elegant algorithm to mix the elements in two arrays (of potentially differing sizes) so that the items are drawn in an alternating fashion from each array, with the leftovers added to the end?
E.g.
Array 1 - A, B, C, D, E, F, G
Array 2 - 1, 2, 3, 4
Mixed array - A, 1, B, 2, C, 3, D, 4, E, F, G
I would prefer the solution in C#, but I should be able to read and transpose solutions in any language (or even some form of pseudo code).
Don't worry about null checking or any other edge cases, I'll handle those.
QUESTION 14The process of combining/merging of the two sorted arrays into the third array in sorted form (without. sorting) without any duplicate element is known as merge sort.
You can try printing the second array with a second statement or concatenating the string representations of the two arrays and printing that string in a single statement. The following may be useful in getting the string representation of the arrays: Arrays. toString(array) . Show activity on this post.
You mean something along the lines of this?
// naive/boring approach
int i = 0;
int m = 0;
while (i < a1.size() || i < a2.size()) {
if (i < a1.size())
mixed[m++] = a1[i];
if (i < a2.size())
mixed[m++] = a2[i];
i++;
}
If you use this, you'll probably want to store the array lengths in variables so you don't have to keep calling a size() method (or whatever it is in whatever language you use).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With