Linear search and bubble sort · 线性查找与冒泡排序
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Find one mark, then order the list
- Syllabus topic 10.2 asks for two algorithms on an array: a linear search and a bubble sort.
- A linear search looks at every cell. Remember the index when the value matches. If it never matches, the index stays 0.
- Searching does not move the values. Sorting does.
中文
先找到一个分数,再把列表排好
- 考纲 10.2 要求数组上的两个算法:线性查找和冒泡排序。
- 线性查找查看每一个单元。值相等时记下下标。始终没有相等,下标就保持 0。
- 查找不移动数据。排序会移动。
DECLARE A : ARRAY[1:4] OF INTEGER
DECLARE I, Pos : INTEGER
A[1] ← 4
A[2] ← 9
A[3] ← 1
A[4] ← 7
Pos ← 0
FOR I ← 1 TO 4
IF A[I] = 9 THEN
Pos ← I
ENDIF
NEXT I
OUTPUT Pos
English
Bubble the largest to the end
- Compare each pair of neighbours. When the left one is larger, swap them through a temporary variable.
- One comparison is not the whole sort. Repeat the pass until every pair has been handled.
- For four values, an outer loop of three passes and an inner loop across the pairs is enough.
中文
把最大的冒到末尾
- 比较每一对相邻的值。左边更大时,用一个临时变量交换它们。
- 一次比较不是整个排序。把这一趟重复到每一对都处理过。
- 四个值时,外层三趟、内层走过各对,就够了。
DECLARE Score : ARRAY[1:4] OF INTEGER
DECLARE I, J, Temp : INTEGER
Score[1] ← 4
Score[2] ← 1
Score[3] ← 3
Score[4] ← 2
FOR I ← 1 TO 3
FOR J ← 1 TO 3
IF Score[J] > Score[J + 1] THEN
Temp ← Score[J]
Score[J] ← Score[J + 1]
Score[J + 1] ← Temp
ENDIF
NEXT J
NEXT I
OUTPUT Score[1]
OUTPUT Score[2]
OUTPUT Score[3]
OUTPUT Score[4]
English
Common mistakes
- A swap needs three assignments. Copying the right cell over the left one loses the left value.
THENstays on theIFline in this guide. The innerNEXTnamesJ, the outer namesI.
中文
常见错误
- 交换需要三次赋值。把右边的单元直接抄到左边,左边的值就丢了。
- 这份指南里
THEN留在IF那一行。内层NEXT写J,外层写I。
English
Now you try
- First report where
9sits. Then sort four values into ascending order, one per line.
中文
现在你来试
- 先报告
9在哪一格。再把四个值排成升序,每个值单独一行。
The array A holds · 持有 4, 9, 1, 7. Set Pos to the index of 9 (it is 2) and output Pos. If you never find it, Pos stays 0. · 数组 A 里是 4、9、1、7。把 Pos 设为 9 的下标(是 2)并输出 Pos。如果没找到,Pos 保持 0。
Click Run to see the output here. · 点击“运行”查看此处输出。
The array Score holds · 持有 4, 1, 3, 2. Bubble-sort it into ascending order and output the four values, one per line. · 数组 Score 里是 4、1、3、2。用冒泡排序排成升序,并把四个值各输出一行。
Click Run to see the output here. · 点击“运行”查看此处输出。