Sắp xếp nổi bọt
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
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.
English
Swapping two values
- To sort, you must swap two items.
- Python can swap in one line:
a, b = b, a.
English
left = "pear"
right = "apple"
temp = left # save the left value first
left = right
right = temp
print(left, right) # apple pear
- Python's one-line swap does the same job:
left, right = right, left. - The exam's pseudocode swaps through
Temp, so know both forms. Withouttemp,left = rightloses"pear".
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.

English
heights = [160, 152, 171, 148, 165]
for i in range(len(heights) - 1):
for j in range(len(heights) - 1 - i):
if heights[j] > heights[j + 1]:
heights[j], heights[j + 1] = heights[j + 1], heights[j]
print("after pass", i + 1, heights)
after pass 1 [152, 160, 148, 165, 171]
after pass 2 [152, 148, 160, 165, 171]
after pass 3 [148, 152, 160, 165, 171]
after pass 4 [148, 152, 160, 165, 171]
- 5 values need 4 passes. After pass 1, the largest (171) is at the end, so each later pass can stop one place earlier (
- i). - To sort from largest to smallest, change
>to<.
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
Khám phá
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.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Swap the values of a và b, so that afterwards a là (is) 9 và b là (is) 5.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Sort the list nums thành tăng dần order (smallest first) using a bubble sort. The result should be [1, 2, 4, 5].
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write is_sorted(nums) that returns True if the list is already in ascending order, otherwise False.
Nhấn Chạy để xem kết quả ở đây.