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
Sorting puts items in order
- Sorting rearranges a list into order — smallest to largest, say.
- Bubble sort is the standard method named in the syllabus.
- It compares neighbours and swaps any that are the wrong way round.
中文
排序把元素排好顺序
- 排序(sorting)把列表重新排成某种顺序 —— 比如从小到大。
- 冒泡排序(bubble sort)是考纲里点名的标准方法。
- 它比较相邻的两个元素,把顺序反了的交换过来。
English
Swapping two values
- To sort, you must swap two items.
- Python can swap in one line:
a, b = b, a.
中文
交换两个值
- 要排序,就必须交换(swap)两个元素。
- Python 可以一行完成交换:
a, b = b, a。
a = 5
b = 9
a, b = b, a
print(a, b) # 9 5
English
Bubble sort: compare neighbours
- Walk the list comparing each pair of neighbours.
- If the left one is bigger, swap them — the biggest "bubbles" to the end.
- Repeat the passes until the list is in order.
中文
冒泡排序:比较相邻元素
- 遍历列表,逐对比较相邻元素。
- 如果左边更大,就交换 —— 最大的会一路“冒泡”到末尾。
- 重复几轮,直到列表有序。
nums = [5, 1, 4, 2]
for i in range(len(nums) - 1):
for j in range(len(nums) - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums) # [1, 2, 4, 5]
English
In the exam: bubble sort
- The exam writes bubble sort in pseudocode with nested loops and a swap.
中文
在考试里:冒泡排序
- 考试用伪代码写冒泡排序:嵌套循环加一次交换。
FOR I ← 1 TO N - 1
FOR J ← 1 TO N - 1
IF List[J] > List[J + 1]
THEN
Temp ← List[J]
List[J] ← List[J + 1]
List[J + 1] ← Temp
ENDIF
NEXT J
NEXT I
Explore · 探索
Watch bubble sort work · 看冒泡排序如何工作
Compare neighbours and swap any out of order; the biggest bubbles to the end. · 比较相邻两项,顺序错就交换;最大的会冒到末尾。
English
Common mistakes
- Each pass moves the largest remaining value to the end.
- If a whole pass makes no swaps, the list is already sorted.
中文
常见错误
- 每一趟把剩下的最大值移到末尾。
- 如果一整趟都没有交换,列表就已经排好了。
English
Now you try
- Swap two values, then sort a whole list.
- Press Check answer to test your code.
中文
现在轮到你
- 先交换两个值,再给整个列表排序。
- 按检查答案来测试你的代码。
Swap the values of a and b, so that afterwards a is 9 and b is 5. · 交换 a 和 b 的值,使得之后 a 是 9、b 是 5。
Click Run to see the output here. · 点击“运行”查看此处输出。
Sort the list nums into · 生成 ascending · 升序 order (smallest first) using a bubble sort. The result should be [1, 2, 4, 5]. · 用冒泡排序把列表 nums 排成升序(最小在前)。结果应为 [1, 2, 4, 5]。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write is_sorted(nums) that returns True if the list is already in ascending order, otherwise False. · 写一个 is_sorted(nums),如果列表已经是升序就返回 True,否则返回 False。
Click Run to see the output here. · 点击“运行”查看此处输出。