Sorting and searching · Exercise 59 of 100
Mergesort
Split the array into halves until each piece has at most one value, then merge pairs of sorted pieces. The smallest remaining value must be at the front of one of the two pieces, so compare their fronts and take the smaller value, taking from the left on a tie. When one piece runs out, copy the rest of the other piece.
Try it yourself
In the final merge of [2, 5, 8] and [1, 5, 9], take from the left piece on a tie. How many times do you compare two front values before one piece runs out?
One-step hint
Point to the front of each piece and tally once per comparison. On equal fronts, advance the left pointer only. Stop tallying when either pointer runs out.
Worked solution
- Compare 2 with 1 and take 1. Compare 2 with 5 and take 2. The third comparison is a tie, so take the left 5.
- Compare 8 with the right 5 and take 5, then compare 8 with 9 and take 8. The left piece is now empty after 5 comparisons, so copy 9 directly.