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.
정렬은 항목을 순서대로 배치합니다
- 정렬(Sorting) 은 리스트를最小的从大到小或从小到大等顺序重新排列——例如,从最小到最大。
- 버블 정렬(Bubble sort) 은 syllabus에서 명시된 표준 방법입니다.
- 인접한元素를 비교하고, 순서가颠倒的 ones을交换。
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
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.
버블 정렬: 인접한 요소 비교
- 리스트를 traversal하며 각 인접한 쌍을 비교합니다.
- 왼쪽이 크면 교체합니다—가장 큰 값이 "거품"처럼 끝으로 이동합니다.
- 리스트가 정렬될 때까지 passes를 반복합니다.
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.
시험 준비: 버블 정렬
- 시험에서는 중첩 루프와 교체를 사용하는 가구문(pseudocode)으로 버블 정렬을 작성합니다.
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.
흔한 실수
- 각 pass마다 Remaining한 가장 큰 값을 끝으로 이동시킵니다.
- 한 pass 전체에 걸쳐 교체가 없으면, 리스트는 이미 정렬되어 있는 것입니다.
Now you try
- Swap two values, then sort a whole list.
- Press Check answer to test your code.
이제 직접 해보기
- 두 값을 교체한 후, 전체 리스트를 정렬합니다.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
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)을 작성하십시오. list가 이미 오름차순으로 정렬되어 있으면 True을 반환하고, 그렇지 않으면 False를 반환합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.