KS48525 3.1.4 32 min read 10 question quiz 19 exam marks

Sorting Algorithms

Bubble sort and merge sort traced pass by pass, why merge sort wins on large lists, and how to answer the compare question without repeating yourself.

Bubble sort

A bubble sort works through the list comparing each pair of adjacent items and swapping them if they are in the wrong order. Each complete pass through the list is called a pass, and after each pass the largest remaining value has moved to its final position at the end.

The name comes from that behaviour: large values rise to the end of the list like bubbles rising to the surface.

Traced properly

Sorting [5, 3, 8, 1] into ascending order.

Pass 1

CompareList after the comparison
5 and 3, swap3, 5, 8, 1
5 and 8, no swap3, 5, 8, 1
8 and 1, swap3, 5, 1, 8

8 is now in its final position, so the next pass does not need to look at it.

Pass 2

CompareList after the comparison
3 and 5, no swap3, 5, 1, 8
5 and 1, swap3, 1, 5, 8

Pass 3

CompareList after the comparison
3 and 1, swap1, 3, 5, 8

A pass then completes with no swaps at all, which tells the algorithm the list is sorted and it stops.

The stopping condition

A bubble sort finishes when a complete pass is made with no swaps. Mentioning this earns a mark, because it is the only way the algorithm knows it is done.

AQA PSEUDO-CODE
SUBROUTINE bubbleSort(items)
    swapped ← True
    WHILE swapped = True
        swapped ← False
        FOR i ← 0 TO LEN(items) - 2
            IF items[i] > items[i + 1] THEN
                temp ← items[i]
                items[i] ← items[i + 1]
                items[i + 1] ← temp
                swapped ← True
            ENDIF
        ENDFOR
    ENDWHILE
    RETURN items
ENDSUBROUTINE

What is good and bad about it

  • Good: very simple to write and understand, and it needs almost no extra memory because items are swapped inside the original list.
  • Bad: slow on large lists. Sorting n items takes roughly n squared comparisons, so ten times more data means about a hundred times more work.
Bubble sort worked through pass by passBubble sort applied to the list 5, 1, 4, 2, 8. In pass one the algorithm compares each neighbouring pair from the left. It compares 5 and 1, 5 is bigger so they swap, giving 1, 5, 4, 2, 8. It compares 5 and 4 and swaps, giving 1, 4, 5, 2, 8. It compares 5 and 2 and swaps, giving 1, 4, 2, 5, 8. It compares 5 and 8, 5 is smaller so nothing moves, and the largest value 8 has bubbled to the end and is now in its final place. Pass two makes one swap, of 4 and 2, giving 1, 2, 4, 5, 8, and 5 is now also in place. Pass three makes no swaps at all, which tells the algorithm the list is sorted and it can stop.Bubble sort on 5, 1, 4, 2, 8start51428pass 1514285 is bigger than 1, so swap154285 is bigger than 4, so swap145285 is bigger than 2, so swap142585 is smaller than 8, leave itpass 212458one swap this pass, 5 is now in placepass 312458no swaps at all, so the list is sorted
After pass one the largest value is definitely at the end. After pass two the two largest are. A pass with no swaps means the list is sorted.
Bubble sort on 5, 2, 4, 1, 3Bubble sort drawn with numbered cards. On the left is the first pass, step by step. The two cards being compared are lit up. 5 is bigger than 2, so they swap. 5 is bigger than 4, so they swap again. 5 is bigger than 1 and then 3, and swaps each time, so the 5 has bubbled all the way to the end, where it is in its final place and is shown in green. On the right is the list after every pass: after pass 1 the 5 is in place, after pass 2 the 4 and 5, and after pass 3 the whole list is in order. Pass 4 makes no swaps at all, which is how the algorithm knows it can stop.One pass, step by step524135 > 2: swap254135 > 4: swap245135 > 1: swap241535 > 3: swap241355 is in place123After every passstart52413pass 124135pass 221345pass 312345pass 412345pass 4 made no swaps,so the list is sortedstop when a pass makes no swaps4
  1. Compare two neighbours, and if they are the wrong way round, swap them.
  2. Work along the list. A big value is carried all the way to the end.
  3. After a pass the last item is in its final place, so the next pass can be shorter.
  4. Repeat until a whole pass makes no swaps.
Each pass puts one more item in place. A pass with no swaps means the list is sorted.

Merge sort

A merge sort repeatedly splits the list in half until every sub list contains one item, then merges the sub lists back together in order.

A list of one item is by definition already sorted, which is what makes the strategy work. All the actual sorting happens during the merging.

The two phases

Split: divide the list in half, then halve each half, and keep going until every sub list holds a single item.

       7  3  9  1  5  2
      /                \
  7  3  9            1  5  2
  /     \            /     \
7      3  9        1      5  2
       /   \              /   \
      3     9            5     2

Merge: take pairs of sub lists and combine them by repeatedly comparing the front item of each and taking the smaller.

3 + 9   ->  3 9
5 + 2   ->  2 5
7 + 3 9 ->  3 7 9
1 + 2 5 ->  1 2 5
3 7 9 + 1 2 5 -> 1 2 3 5 7 9

Look closely at the last merge. Compare 3 and 1, take 1. Compare 3 and 2, take 2. Compare 3 and 5, take 3. Compare 7 and 5, take 5. Compare 7 and nothing left on the right, so take 7 then 9. Six comparisons to merge six items, and that is the pattern: each merge costs roughly as many comparisons as there are items in it.

Why merge sort is fast

There are only about log n rounds of merging, because the list can only be halved that many times, and each round costs about n comparisons. Doubling the data therefore roughly doubles the work rather than quadrupling it.

Merge sort: the divide phase and the merge phaseMerge sort on the list 38, 27, 43, 3, 9, 82, 10, 1. The divide phase splits the list in half repeatedly: first into 38, 27, 43, 3 and 9, 82, 10, 1; then into 38, 27 and 43, 3 and 9, 82 and 10, 1; then into eight single item lists. A list of one item is already sorted. The merge phase then combines pairs, each time comparing the front items of the two lists and taking the smaller. The pairs become 27, 38 and 3, 43 and 9, 82 and 1, 10. Those merge into 3, 27, 38, 43 and 1, 9, 10, 82. Those merge into the final sorted list 1, 3, 9, 10, 27, 38, 43, 82.DIVIDE: split in half until every list holds one item3827433982101382743398210138274339821013827433982101273834398211032738431910821391027384382MERGE: rebuild in pairs, always taking the smaller front item
Merge sort always takes about n log n comparisons, whatever order the list starts in, but it needs extra memory to hold the part lists.

Sorting algorithm visualiser

Run bubble, insertion, merge and quick sort side by side and count the comparisons. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Merge sort on eight numbers: divide, then mergeMerge sort drawn as a diamond of numbered cards, read from the top down and then back up. The list of eight numbers, 6 3 8 1 7 2 5 4, is divided in half again and again: first into two groups of four, then four groups of two, then eight single cards. A single card is already sorted. Then the groups are merged back together, working upwards. Each merge compares the front card of the two groups and takes the smaller one every time, so the pairs become 3 6, 1 8, 2 7 and 4 5, then the groups of four become 1 3 6 8 and 2 4 5 7, and finally the whole list is merged into 1 2 3 4 5 6 7 8.63817254638172546381725463817254361827451368245712345678dividemerge1 item is sortedto merge:compare thefront of eachgroup, take thesmaller one123
  1. Divide the list in half, again and again.
  2. Stop when every group is a single item. One item is already sorted.
  3. Merge groups back together, taking the smaller front item each time, until one sorted list is left.
Merge sort divides until the pieces are trivial, then does all its real work while merging.

Comparing the two

This comparison is examined almost every year and the marks come from giving different points rather than repeating one point in three ways.

Bubble sortMerge sort
MethodRepeatedly swaps adjacent itemsSplits into single items then merges in order
Efficiency on large listsPoor, roughly n squared comparisonsGood, roughly n log n comparisons
Memory usedVery little, sorts in placeMore, because sub lists are held in memory during merging
Ease of writingSimple, few linesMore complex, usually recursive
Best useVery small lists, or lists that are almost sorted alreadyLarge lists where speed matters

How to structure the answer

An examiner wants a genuine trade off, not a preference. The structure that always scores is:

  1. Merge sort is more efficient on large lists, and say why: it halves the problem instead of walking the whole list on every pass.
  2. Bubble sort uses less memory, and say why: it swaps items inside the existing list rather than building new sub lists.
  3. Conclude by naming the condition that decides it: list size and available memory.
Do not say bubble sort is 'useless'

On a list of eight items, or on a list that is already nearly in order, a bubble sort finishes almost immediately and needs no extra memory. Blanket statements lose the evaluation marks.

Number of passes questions

If asked how many passes a bubble sort needs on a list of n items, the answer is at most n minus 1, because after n minus 1 items are in place the last one has nowhere else to be.

Key terms you must be able to define

Bubble sort
A sort that repeatedly compares adjacent items and swaps them if they are in the wrong order until a pass produces no swaps.
Pass
One complete run through the list by a bubble sort, after which the largest remaining item is in its final position.
Swap
Exchanging the positions of two adjacent items, which requires a temporary variable to avoid losing one of the values.
Merge sort
A sort that divides the list into single item sub lists and then repeatedly merges pairs of sub lists in order.
Merge
Combining two sorted sub lists into one sorted list by repeatedly taking the smaller of the two front items.
In place
Sorting that rearranges the original list without needing significant extra memory, as a bubble sort does.
Divide and conquer
The strategy of splitting a problem into smaller parts, solving each, and combining the results, as merge sort does.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineBubble sort
AnswerA sort that repeatedly compares adjacent items and swaps them if they are in the wrong order until a pass produces no swaps.
DefinePass
AnswerOne complete run through the list by a bubble sort, after which the largest remaining item is in its final position.
DefineSwap
AnswerExchanging the positions of two adjacent items, which requires a temporary variable to avoid losing one of the values.
DefineMerge sort
AnswerA sort that divides the list into single item sub lists and then repeatedly merges pairs of sub lists in order.
DefineMerge
AnswerCombining two sorted sub lists into one sorted list by repeatedly taking the smaller of the two front items.
DefineIn place
AnswerSorting that rearranges the original list without needing significant extra memory, as a bubble sort does.
DefineDivide and conquer
AnswerThe strategy of splitting a problem into smaller parts, solving each, and combining the results, as merge sort does.

Reach the top grade on this topic

The trace marks are free if you are systematic, and the comparison marks are where grades are decided.

Show every pass, not every swap. When asked to show the list after each pass, write the state of the whole list at the end of each complete pass. Writing every individual swap wastes time and often loses the mark because the examiner cannot find the pass boundaries.

Give the reason with the property. "Merge sort is faster" is not a mark. "Merge sort is faster on large lists because halving the list means the number of rounds grows very slowly, while a bubble sort has to walk the whole list once per pass" is two.

Always concede something. An evaluation that says merge sort is better in every way is wrong: it uses more memory and is harder to implement. Naming that cost is what moves an answer into the top band.

  • Trace a bubble sort on six items showing the list at the end of each pass
  • Trace a merge sort showing both the splitting and the merging stages
  • State the stopping condition of a bubble sort
  • Give three genuinely different points of comparison between the two algorithms

Mistakes that cost marks here

Avoid these
  • Showing the list after each swap rather than after each pass when the question asks for passes.
  • Forgetting the temporary variable when describing a swap, which would overwrite one of the two values.
  • Saying merge sort sorts each half and then joins them, without explaining that the halving continues until each sub list holds one item.
  • Claiming merge sort is better in every respect. It needs more memory and is harder to program.
  • Saying a bubble sort finishes after a fixed number of passes. It finishes when a pass completes with no swaps, which may be sooner.
Fun fact

Merge sort was described by John von Neumann in 1945, on the same machine project that gave us the stored program computer. It is still the algorithm behind the sort routines in several standard libraries today, eighty years later.

Knowledge check

0 of 10 answered
1After one complete pass of a bubble sort in ascending order, which item is guaranteed to be in its final position?
2What tells a bubble sort that the list is now sorted?
3In a merge sort, what is the list repeatedly divided into?
4During the merge stage, how is the next item chosen?
5Which sort generally requires more memory?
6How many passes at most does a bubble sort need on a list of 6 items?
7Which statement about bubble sort is correct?
8Roughly how does the work done by a bubble sort grow when the list size is doubled?
9A merge sort is applied to [8, 2, 5, 1]. What are the sub lists immediately before merging begins?
10Which situation most favours a bubble sort over a merge sort?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

19 marks
1Describe how a bubble sort sorts a list of numbers into ascending order.4 marks
Describe

Mark scheme0 / 4
  • LAdjacent pairs of items are compared
  • LIf they are in the wrong order they are swapped
  • LThis is repeated for the whole list, which is called a pass
  • LPasses continue until a pass is completed with no swaps
Model answer

A bubble sort starts at the beginning of the list and compares the first two items. If they are in the wrong order it swaps them, then moves along one position and compares the next adjacent pair, continuing to the end of the list. One complete journey through the list is called a pass, and at the end of each pass the largest remaining value has been carried to its correct position at the end. The algorithm then begins another pass, and it keeps going until a whole pass is completed without a single swap being made, which shows that no pair is out of order and the list is sorted.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Describe how a merge sort works.4 marks
Describe

Mark scheme0 / 4
  • LThe list is repeatedly divided in half
  • LUntil each sub list contains only one item
  • LPairs of sub lists are then merged back together
  • LDuring each merge the smaller of the two front items is taken first, so the result stays in order
Model answer

A merge sort repeatedly divides the list in half, then divides each half in half, and continues until every sub list contains only one item, at which point every sub list is trivially in order. It then merges the sub lists back together in pairs. To merge two sub lists it compares the item at the front of each and takes whichever is smaller, repeating until one sub list is empty and then taking whatever is left in the other. Because both inputs to every merge are already sorted, the merged result is sorted too, and after the final merge the whole list is in order.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3The list [6, 2, 9, 4] is sorted using a bubble sort. Show the contents of the list after each of the first two passes.2 marks
Write

Mark scheme0 / 2
  • LAfter pass 1 the list is 2, 6, 4, 9
  • LAfter pass 2 the list is 2, 4, 6, 9
Model answer

During the first pass 6 and 2 are swapped to give 2, 6, 9, 4, then 6 and 9 are left alone, then 9 and 4 are swapped, so the list after pass one is 2, 6, 4, 9. During the second pass 2 and 6 are left alone, then 6 and 4 are swapped, so the list after pass two is 2, 4, 6, 9.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Compare a bubble sort and a merge sort. Your answer should refer to efficiency and memory use.6 marks
Compare

Mark scheme0 / 6
  • LA bubble sort repeatedly swaps adjacent items, while a merge sort divides the list and merges it back
  • LA merge sort is more efficient on large lists
  • LBecause halving the list means the number of rounds grows very slowly as the list grows
  • LA bubble sort needs roughly n squared comparisons, so doubling the data quadruples the work
  • LA bubble sort uses less memory because it sorts in place
  • LA merge sort needs additional memory to hold the sub lists while merging
Model answer

A bubble sort works by repeatedly comparing adjacent pairs of items and swapping any that are in the wrong order, whereas a merge sort divides the list until each sub list holds one item and then merges the sub lists back together in order. On large lists a merge sort is considerably more efficient, because each round of merging halves the number of sub lists, so the number of rounds grows extremely slowly even as the list becomes very large. A bubble sort has to walk the whole list once per pass and may need almost as many passes as there are items, which means roughly n squared comparisons, so doubling the size of the list roughly quadruples the work. The trade off is memory. A bubble sort rearranges items inside the original list and so needs almost no extra memory, while a merge sort has to hold the sub lists it is building as well as the original data. For a small list, or on a device with very little memory, a bubble sort is therefore a reasonable choice, but for a large list where speed matters a merge sort is far better.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why a bubble sort may need fewer passes on a list that is already almost in order.3 marks
Explain

Mark scheme0 / 3
  • LA bubble sort stops when a pass completes with no swaps
  • LAn almost sorted list needs few swaps, so that condition is reached quickly
  • LSo the algorithm can finish after only one or two passes rather than n minus 1
Model answer

A bubble sort does not run a fixed number of passes. It keeps making passes until one complete pass finishes without a single swap, because that shows no adjacent pair is out of order and the list must therefore be sorted. If the list is already almost in order then very few items need swapping, so the algorithm reaches a swap free pass after only one or two passes rather than after the n minus 1 passes it would need in the worst case. This is one of the few situations in which a bubble sort performs well.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 19