Computer Science Essentials, Unit 1, Lesson 4 of 7

Insertion sort and merge sort

About 3 min to read, then 7 practice questions

Insertion sort

An insertion sort treats the first item as a sorted list of one.

Each pass takes the next item and slides it left into the right place in the sorted part.

  • Pass 1 inserts the second item, pass 2 the third, and so on: a list of n items takes n − 1 passes.
  • Items in the sorted part that are bigger than the new item each move one place right.
  • It is quick when the list is already nearly in order.

A worked example: an insertion sort on 31, 8, 19, 4, 26, into ascending order.

  1. Start: the sorted part is just 31. The list is 31, 8, 19, 4, 26.

After pass k, the first k + 1 items are in order and the items after them have not moved yet. That is how you can tell an insertion sort from a bubble sort: a bubble sort moves the largest item to the end in its first pass.

Merge sort

A merge sort splits the list into single items, then merges them back together in order.

It has two stages.

  1. Split the list in half, and split each half again, until every list holds one item. A list of one item is sorted.

In this course, when a list has an odd number of items, the left half takes the extra one. A question usually shows you how the list was split; follow what they show.

When you merge two lists and one runs out, copy the rest of the other across without comparing.

A worked example: merge [5, 23, 40] and [12, 18, 51]. Each step compares the two front items and takes the smaller one.

  1. 5 vs 12: take 5. Merged so far: 5.

The rounds of merging, for 8 items such as 61, 14, 35, 9, 70, 22, 48, 3:

  1. Split down to single items: [61] [14] [35] [9] [70] [22] [48] [3].

The split never changes the order of the items: it only cuts the list into pieces. The left half of [61, 14, 35, 9, 70, 22, 48, 3] is [61, 14, 35, 9].

Comparing the three

Bubble sortInsertion sortMerge sort
How it worksSwap neighbours, pass after passSlide each item into a sorted partSplit, then merge in order
Long random listSlowSlowFast
Nearly sorted listFairly quick (stops early)QuickNo faster
Extra memoryVery littleVery littleMore, for the merged lists
Ease of writingEasyEasyHarder (often recursive: the code calls itself on each half)

Merge sort needs extra memory because it builds new lists while it merges. Bubble sort and insertion sort sort the list where it is, so they need very little extra memory.

To write these in Python, see Insertion sort and merge sort on Brainlag Code.

Practise this

7 questions, about 7 min

  • XP for each right first time
  • Fills in your course map

Sign in to keep your progress.

Start practising