DSA Factory
Free Sorting lessonsSorting · Stage 2 · Merge sort and counting · Step 2

Split, sort the halves, merge

Sort a list by splitting it in two, sorting each half the same way, and merging the results. About 15 minutes.

Trust the smaller sorts

Here's the whole idea. To sort a list, cut it in half. Sort the left half, sort the right half, and merge the two sorted halves into one. You already know how to merge.

How do you sort each half? The same way, by cutting it in half again. You keep cutting until each piece has just one value, and a single value is already sorted. Then the merges build the answer back up, one level at a time.

Split: until each piece has one value.
Merge: pieces back together, level by level.
In code
mid = len(nums) // 2
left = nums[:mid]
right = nums[mid:]
Merge sort on [8, 3, 6, 1, 4].
8
0
3
1
6
2
1
3
4
4
leftright

Start with the whole list. Cut it in half: [8, 3] and [6, 1, 4].

Move 1 of 4

Why n times log n

Look at the levels. The top level merges one list of n values. The next has two lists of n over 2, together still n values. The one after that has four lists, still n values in total. Each level costs about n, and halving n down to 1 takes log n levels.

So total work is n times log n, always. Even a reversed list takes the same, because the splits don't depend on the values.

Each level: touches every value once.
Halving: gives about log n levels.
Quick check

A list has 1,000 values. Roughly how many levels of splitting does merge sort do?

  1. AAbout 10, since halving 1,000 reaches 1 after about 10 steps
  2. B1,000, one per value
  3. C2, one split and one merge
Show the answer

About 10, since halving 1,000 reaches 1 after about 10 steps. Each split halves the pieces, and 2 to the power of 10 is about 1,000.

Your problem

Merge sort

nums is a list of whole numbers. Return the list sorted from smallest to largest. Use the split, sort the halves, merge idea.

Example
nums = [5, 2, 4, 1, 3] → [1, 2, 3, 4, 5]

0 ≤ length ≤ 3,000 · −1,000,000 ≤ value ≤ 1,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve