Algorithms · GCSE · OCR J277 2.1.3, AQA 8525 3.1.4, Edexcel 1CP2 1.2.6 · about 15 min
Passes and swaps, stopping early, and hearing a tune become a scale.
[1 mark]What does this program print?
items = [5, 2, 4, 1]
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
print(items)[2, 4, 1, 5]
One pass: the largest item, 5, bubbles to the end.
[1 mark]When can bubble sort stop early?
[1 mark]What does bubble sort compare?
[1 mark]A list of 6 items. How many comparisons does one pass of bubble sort make?
[1 mark]Why does a swap in pseudocode usually need a temporary variable?
Sort notes = [392, 262, 523, 330, 294, 440, 349, 494] with bubble sort, written yourself (no sort or sorted). Then print sorted: <the list> and play every note of the sorted list for 0.2 seconds.
# the two lines every program starts with: the commands, then the robot from bugbot import * connect() notes = [392, 262, 523, 330, 294, 440, 349, 494]
The hint students can ask for: Go through the list comparing each pair of neighbours and swapping them when they are the wrong way round. Repeat until a whole pass makes no swaps.
from bugbot import *
connect()
notes = [392, 262, 523, 330, 294, 440, 349, 494]
swapped = True
while swapped:
swapped = False
for i in range(len(notes) - 1):
if notes[i] > notes[i + 1]:
notes[i], notes[i + 1] = notes[i + 1], notes[i]
swapped = True
print("sorted:", notes)
for note in notes:
tone(note, 0.2)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.