Bubble sort
Python for IGCSE CS Lesson 11 2:02 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Every sort is built on one move: exchanging two values.
每一种排序都建立在一个动作上:交换两个值。
Python has a shortcut that does it in a single line.
Python 有一个捷径,一行就能做到。
The exam does not, and wants three lines and a temporary — so learn that version too.
考卷没有这个捷径,它要的是三行加一个临时变量—— 所以那种写法也要学会。
The reason is worth knowing: without a temporary, the first assignment overwrites a value you still need, and you end up with the same number twice.
原因值得知道: 没有临时变量,第一次赋值就会覆盖掉你还要用的那个值, 最后你会得到同一个数字两次。
Bubble sort only ever looks at neighbours.
冒泡排序永远只看相邻的两个。
Compare the first two: five and two are the wrong way round, so swap.
比较头两个:5 和 2 顺序反了,交换。
Move along to the next pair — five and four, swap again.
往前挪到下一对——5 和 4,再交换。
Then five and one, swap once more.
然后是 5 和 1,再换一次。
Watch what happened to the five: compared, moved, compared again, and carried to the end of the list.
看看 5 经历了什么: 被比较、被移动、又被比较,最后一路被带到了列表的末尾。
That travelling is where the name comes from.
这一路的"上浮",正是这个名字的由来。
One pass is not a sort.
一趟并不等于排好序。
After the first, the five is home but the rest is still not sorted.
第一趟之后,5 到位了,但其余部分还没有排好。
So you go again, and each pass puts one more into place.
所以你再来一趟,每一趟又把一个值送到它该在的位置。
After the third, the list is in order at last.
第三趟之后,列表终于有序了。
That means the whole algorithm is a loop around the pass — a nested loop, the same shape you met with the grid.
这意味着整个算法是"在一趟外面再套一个循环"—— 一个嵌套循环,和你在网格那一课见过的形状一样。
Here is the whole sort in both notations.
这是完整的排序,两种写法并排。
Two loops and a comparison, and that is the algorithm the syllabus names.
两个循环加一次比较,这就是考纲点名的那个算法。
One refinement worth knowing: if a whole pass makes no swaps at all, nothing was out of order, so the list is already sorted and you can stop early.
有一个改进值得知道: 如果一整趟下来一次交换都没有发生,说明没有任何一对是乱的, 那么列表已经有序,你可以提前停下。
That check is also exactly what the third task asks you to write.
而这个判断,正好也是第三道题要你写的东西。
Four things to take with you.
带走四点。
One: bubble sort compares neighbours and swaps them.
第一:冒泡排序比较相邻的两个并交换它们。
Two: each pass carries one more value to the end.
第二:每一趟把一个值送到末尾。
Three: so the sort needs a loop around the pass.
第三:所以排序需要在"一趟"外面再套一个循环。
Four: a pass with no swaps means the list is sorted.
第四:一趟里一次交换都没有,就说明列表已经有序。
Now do the three tasks.
现在去做那三道题。