Algorithms · GCSE · OCR J277 2.1.3, AQA 8525 3.1.2, Edexcel 1CP2 1.2.7 · about 20 min
Splitting and merging, and choosing between the searches and sorts.
[1 mark]What does this program print?
left, right = [2, 8], [3, 4, 20]
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i]); i = i + 1
else:
result.append(right[j]); j = j + 1
print(result + left[i:] + right[j:])[2, 3, 4, 8, 20]
Merging compares only the front items, then adds what is left over.
[1 mark]Put the stages of merge sort in order.
Number the lines 1 to 4 to put them in the right order.
Keep splitting until every part has one itemMerge pairs of parts into sorted partsKeep merging until one sorted list is leftSplit the list in halfSplit the list in half Keep splitting until every part has one item Merge pairs of parts into sorted parts Keep merging until one sorted list is left
Divide first, then conquer by merging.
[1 mark]Why is merge sort usually faster than bubble sort on large lists?
[1 mark]What is a disadvantage of merge sort compared with bubble sort?
[1 mark]A school has 2 million sorted records and searches them thousands of times a day. Which search should it use?
Two robots each played a sorted tune: left = [262, 330, 440, 523] and right = [294, 349, 392, 494]. Write merge(left, right) yourself (no sort or sorted) and use it to make one sorted tune. Print merged: <the list> and play every note for 0.2 seconds.
# the two lines every program starts with: the commands, then the robot from bugbot import * connect() left = [262, 330, 440, 523] right = [294, 349, 392, 494]
The hint students can ask for: Walk both lists at once with a position in each. Take the smaller of the two items in front of you and move that position on. When one list runs out, the rest of the other follows.
from bugbot import *
connect()
left = [262, 330, 440, 523]
right = [294, 349, 392, 494]
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = i + 1
else:
result.append(right[j])
j = j + 1
return result + left[i:] + right[j:]
tune = merge(left, right)
print("merged:", tune)
for note in tune:
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.