bubble sort
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ 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.
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
สำรวจ
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.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Swap the values of a และ b, so that afterwards a เป็น 9 และ b เป็น 5.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Sort the list nums เข้าใน เรียงลำดับเพิ่มขึ้น order (smallest first) using a bubble sort. The result should be [1, 2, 4, 5].
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write is_sorted(nums) that returns True if the list is already in ascending order, otherwise False.
คลิก Run เพื่อดูผลลัพธ์ที่นี่