Sorting and searching · Exercise 61 of 100

Median of two sorted arrays

For two ascending arrays with at least one value between them, repeatedly take the smaller of the two front values, taking either one on a tie. This gives the combined order because each front is the smallest value left in its array, and you can continue along the other array if one runs out. Stop at the middle value for an odd total or average the two middle values for an even total.

Try it yourself

What is the median of the combined values from [1, 4, 4, 12] and [2, 7, 10, 11, 15, 18], counting both copies of 4?

One-step hint

Mark the two central slots in a row for all ten values. Merge up to the second mark, keeping duplicates, then average the two marked entries.

Worked solution
  1. There are 10 values, so count to the fifth and sixth positions. Taking the smaller front each time gives 1, 2, 4, 4 for the first four.
  2. The next fronts are 12 and 7, so take 7, then take 10 ahead of 12. The middle values average to (7 + 10) / 2 = 8.5.
DSA compiler