Classic algorithms · 17 / 22 Exercise Hard

Merge sort

Objective

Merge sort splits the list into two halves, sorts each one recursively and merges them into a sorted list. It is one of the fastest and its time is always O(n log n).

Instructions

  • Read a line with integers separated by spaces.
  • Write merge(a, b), which merges two sorted lists: compare the first remaining elements of each one, take the smaller (if equal, the one from the first list) and, when one runs out, append what is left of the other. Count every comparison between elements.
  • Write a recursive sort_list(items): a list of 0 or 1 elements is already sorted; otherwise split it into len // 2 elements (the left half, with items[:half]) and the rest, sort them and merge them.
  • Show the sorted list and, on another line, Comparisons: c.
Input
5 2 4 7 1 3
Output
1 2 3 4 5 7
Comparisons: 11

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise