Algorithms · GCSE · OCR J277 2.1.3, AQA 8525 3.1.4, Edexcel 1CP2 1.2.6 · about 15 min
Building a sorted part one item at a time, on the robot's readings.
[1 mark]How does insertion sort work?
[1 mark]What does this program print?
items = [31, 15, 51, 20]
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and items[j] > current:
items[j + 1] = items[j]
j = j - 1
items[j + 1] = current
print(items)[15, 20, 31, 51]
Each item is shifted left past bigger ones: the result is in ascending order.
[1 mark]On which kind of list is insertion sort especially quick?
[1 mark]In insertion sort of [31, 15, 51, 20], what does the list look like after the first item is inserted?
Look in eight directions, 45 degrees apart, recording distance() in a list. Sort the list with insertion sort, written yourself (no sort or sorted), printing the list after each insertion. Finally print sorted: <the list>.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
readings = []
for i in range(8):
readings.append(distance())
turn_right(30, angle=45)The hint students can ask for: Take each item in turn as the one to place, and shift the sorted items on its left along until there is a gap for it. Print the list after each item is placed.
from bugbot import *
connect()
readings = []
for i in range(8):
readings.append(distance())
turn_right(30, angle=45)
for i in range(1, len(readings)):
current = readings[i]
j = i - 1
while j >= 0 and readings[j] > current:
readings[j + 1] = readings[j]
j = j - 1
readings[j + 1] = current
print("after inserting", current, ":", readings)
print("sorted:", readings)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.