Seneca

Merge Sort

Computer Science: OCR GCSE, topic 2.1.14

Merge Sort

Merge sort is an example of a divide and conquer algorithm. The problem is broken down into smaller steps.

The concept

The concept

  • We have two packs of cards, which are both already in order.
  • We want to combine the two packs.
  • What can we do?
  • One solution is to only consider the top card of each pile.
  • We then create a new deck, starting with the smaller of the two cards.
  • Repeating the comparison for every card builds one combined, sorted pack.
  • Combining two sorted packs by comparing the top cards is called merge sort.
In English

In English

  • Split the lists into lists of size one.
  • Merge each pair of sublists by comparing the first value of each list.
  • Put the smaller value into the new list first.
  • Continue merging until there is only one list.
  • The first two items of two adjacent lists are always the ones being compared.
  • Some lists may end up one-sided for the final merge.
  • Many more numbers in one list are compared with fewer numbers in another list.
  • The lists do not always need to remain balanced.
Example

Example

  • We will sort the list [12, 5, 9, 1] using merge sort.
  • Step 1: Split the list until each piece has one element.
  • Step 2: Merge [12] and [5].
  • 5 < 12, so 5 comes down.
  • Step 3: Merge [12] and [ ].
  • 12 comes down.
  • Step 4: Merge [9] and [1].
  • 1 comes down.
  • Step 5: Merge [9] and [ ].
  • 9 comes down.
  • Step 6: Merge [5, 12] and [1, 9].
  • Compare first items: 5 > 1, so 1 comes down.
  • Step 7: 5 < 9, so 5 comes down.
  • Step 8: 12 > 9, so 9 comes down.
  • Step 9: 12 comes down.
Pros and cons of merge sort:

Pros and cons of merge sort:

  • Pros:
  • A very efficient algorithm.
  • Cons:
  • Can be slower for small lists.
  • Needs additional memory.

Test yourself on Merge Sort

  • Why could sorting a large list with merge sort cause a problem on a device with very little spare memory?

  • Merge Sort in English

  • Select the true statement about merge sort.

  • Name the three main stages involved in merge sort.

Practise this topic for free