Arrays and strings · Exercise 6 of 100
Merging Sorted Arrays
When two arrays are sorted from smallest to largest, compare their first unused values and take the smaller one. Taking either of two equal values keeps the numbers sorted. When records have labels, follow the stated tie rule to keep those labels in the required order. Once one array runs out, the rest of the other array is already in order.
Try it yourself
Merge [2, 6, 9] and [1, 6, 8] in increasing order, keeping both copies of 6. What is the fifth value?
One-step hint
Point to the first unused value in each list. Copy the smaller one into the next slot, advancing just one pointer even on a tie.
Worked solution
- Take 1 and then 2. The next unused value in each array is 6, so the two copies fill the third and fourth spots.
- The unused values are now 9 and 8. Taking the smaller one puts 8 in the fifth spot.