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
Put the smallest time first
- Three race times sit in an array:
14,9,11. The smallest should come first. - Compare each pair of neighbours. When the left one is larger, swap them.
- That single comparison does not finish the list. The next pair is compared after it.
中文
把最短的时间放在前面
- 三个比赛用时放在数组里:
14、9、11。最小的应该排在最前。 - 比较每一对相邻的值。左边更大时,交换它们。
- 一次比较排不完整个列表。比完这一对,再比下一对。
DECLARE Score : ARRAY[1:3] OF INTEGER
DECLARE J, Temp : INTEGER
Score[1] ← 14
Score[2] ← 9
Score[3] ← 11
FOR J ← 1 TO 2
IF Score[J] > Score[J + 1]
THEN
Temp ← Score[J]
Score[J] ← Score[J + 1]
Score[J + 1] ← Temp
ENDIF
NEXT J
OUTPUT Score[1]
OUTPUT Score[2]
OUTPUT Score[3]
English
Repeat the pass
- One pass of the inner loop bubbles the largest value it sees toward the end.
- The outer loop repeats the pass. For four values, three passes are enough.
- This is the syllabus's bubble sort. A linear search, which you wrote earlier, only looks. A sort rearranges.
中文
再走一趟
- 内层循环走一趟,会把这一趟里最大的值冒到后面。
- 外层循环把这一趟再做几次。四个值,三趟就够了。
- 这就是考纲里的冒泡排序。你之前写的线性查找只是在找。排序会把数据重新排好。
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
Watch out
- Swap with a
Tempvariable.Score[J] ← Score[J + 1]alone deletes the left value. - The inner
NEXTnamesJ. The outerNEXTnamesI.
中文
注意
- 交换要用一个
Temp变量。只写Score[J] ← Score[J + 1]会丢掉左边的值。 - 内层
NEXT写J。外层NEXT写I。
English
Common mistakes
- The test is "left is greater", so the smaller value moves left. The other way sorts into reverse order.
- Arrays in this course count from 1. The last pair is the cell just before the end, and the last cell.
中文
常见错误
- 判断是“左边更大”,这样较小的值才会移到左边。方向反了,就排成了倒序。
- 这门课的数组从 1 开始数。最后一对是末尾前一格和最后一格。
English
Now you try
- The first task is one pass. The second is the full sort. Output each value on its own line.
- Press Check answer to test it.
中文
现在你来试
- 第一题只走一趟。第二题是完整的排序。每个值单独占一行。
- 按检查答案来测试。
The array Score holds · 持有 14, 9, 11. Make one · 一个 pass that swaps a neighbour when the left value is larger. Output the three values, one per line (9, then 11, then 14). · 数组 Score 里是 14、9、11。只走一趟:左边更大时交换相邻项。把三个值各输出一行(9,然后 11,然后 14)。
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. · 点击“运行”查看此处输出。