CleverSphere

Merge sort: the merge step

When merging you always compare the front elements of two sorted lists.

Rules

  • Take the smaller element
  • If one list is empty, append the rest
  • At most n − 1 comparisons

Your turn

Three problems on this topic. Separate lists with commas.

  1. 1 · Merge sort
  2. 2
  3. 3

Merge sort merges two sorted lists. How many comparisons are needed?

[12, 15, 34, 58] [4, 35, 41, 42]

Result (comma-separated)

Comparisons

Separate lists with commas, such as 3, 5, 7. Spaces don’t matter.

Worked example

Merge sort merges two sorted lists. How many comparisons are needed?

[1, 6, 15, 16, 19, 26, 44] [25, 46, 50]

Worked solution

  1. 1Compare the front elements until one list is empty: 8 comparisons.
  2. 2[1, 6, 15, 16, 19, 25, 26, 44, 46, 50]

Typical mistake: Once one list is empty, the rest is appended without further comparisons.

Common questions

Why is merge sort stable?

On a tie you take the element from the left list first.

Related

More topics