Lesson 29: Sort the bays
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Put them in order
- The robot measures 5 parking bays. Each one is a different depth.
- Then it sorts the list from the smallest to the biggest, so the smallest car can go into the shortest bay.
- You write the sort yourself: a bubble sort, one of the standard methods in IGCSE Paper 2.
Words for this lesson
| Word | Meaning |
|---|---|
| sort | put in order, smallest first (ascending) |
| swap | change the places of two values |
| pass | one trip through the whole list |
| ascending | going up: 1, 2, 3 … |
English
One pass
| List before | Compare | Swap? |
|---|---|---|
| 6 3 8 4 | 6 and 3 | yes → 3 6 8 4 |
| 3 6 8 4 | 6 and 8 | no |
| 3 6 8 4 | 8 and 4 | yes → 3 6 4 8 |
- After one pass the biggest value (8) is at the end. The next pass puts 6 in its place.
English
Swap two values
from vexcode_vr import *
def main():
a = [6, 3]
temp = a[0]
a[0] = a[1]
a[1] = temp
brain.print(a)
vr_thread(main)
- The brain prints
[3, 6].tempkeeps the first value safe while it is overwritten.
English
In the exam
- 0478/22/F/M/24 Q3(b): write an algorithm in pseudocode to sort the array
Values[1:50]into ascending order. The mark scheme gives a mark for each of these, and your program has them all: an inner and an outer loop, comparing neighbours, swapping them with a temporary variable, and a stopping condition (no swap in a pass).
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
A car park has 5 bays below the robot, 300 mm apart, and each bay has a different depth. Drive 300 mm to each bay, turn to heading 180 to face into it, and measure with front_distance.get_distance(MM). Add the depth to the list depths as a whole number (with int()), and turn back to heading 90. At the end print the list.
点击“运行”查看此处输出。
难度 5/5 · 今日首次完成可获 400 金币及少量额外奖励
Now sort the depths from the smallest to the biggest with a bubble sort, written by yourself (no sorted() 或 .sort()). Go through the list and compare each pair of neighbours: if the first is bigger, swap them. Repeat the passes until a pass makes no swap. Then print the list.
点击“运行”查看此处输出。