Bubble sort · バブルソート
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.
ソート(並べ替え)で項目を順序付ける
- ソートとは、リストを小さい順から大きい順へと再配置することである。
- バブルソートはカリキュラムで言及されている標準的な手法である。
- 隣り合う要素を比較し、逆になっているものは交換する。
Swapping two values
- To sort, you must swap two items.
- Python can swap in one line:
a, b = b, a.
2つの値の入れ替え
- ソートするためには、2つの要素を交換する必要がある。
- Pythonでは1行で交換できる:
a, b = b, a。
a = 5
b = 9
a, b = b, a
print(a, b) # 9 5
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]
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. · 隣り合う要素を比較し、順序が逆のものは交換します;最も大きな要素が末尾へ移動します。
Common mistakes
- Each pass moves the largest remaining value to the end.
- If a whole pass makes no swaps, the list is already sorted.
よくあるミス
- 各パスで、まだ未処理の最大値が末尾へ移動する。
- 全体のパスで交換が行われない場合、リストは既に整列している。
Now you try
- Swap two values, then sort a whole list.
- Press Check answer to test your code.
あなたも試してみよう
- 2つの値を交換し、その後全体のリストをソートする。
- 回答を確認 を押してコードを試してください。
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. · 実行ボタンをクリックして出力を確認してください。