Sorting algorithms
도입됨
15:34
검색 및 정렬
백만 명의 이름이 있는 전화번호부. 하나씩 확인하면 백만 번의 비교를 할 수도 있습니다. 하지만 이미 그 비법을 알고 있습니다: 중간에서 엽니다…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| sort/sɔːt/ | To arrange items in a list into a chosen order. |
| library/ˈlaɪbrəri/ | A collection of reusable routines that programs can call. |
| algorithm/ˈælɡərɪθəm/ | A finite sequence of precise steps for solving a problem or carrying out a task. |
| bubble sort/ˈbʌbl sɔːt/ | 버블 정렬 |
| insertion sort/ɪnˈsɜːʃn sɔːt/ | 삽입 정렬 |
| list/lɪst/ | A collection of items arranged in a particular order. |
| trace/treɪs/ | To follow an algorithm step by step, recording how its data changes. |
| array/əˈreɪ/ | An indexed collection of elements arranged in one or more dimensions. |
| pass/pæs/ | One complete run through a part of the list during sorting. |
| swap/swɒp/ | To exchange two values so that each takes the other's place. |
| elements/ˈelɪmənts/ | Individual items in a collection or data structure. |
| inner loop/ˈɪnə luːp/ | A loop inside another loop that repeats steps during each pass. |
| flag/flæɡ/ | A stored indicator of a condition or state, often represented by a Boolean value or a single bit. |
| sorted section | The part of a list whose items are already in order. |
| key/kiː/ | The item held aside to be placed into the sorted section. |
| best case | The input that allows an algorithm to complete with the least work. |
| extra memory | Memory used by an algorithm in addition to its input data. |
| in place/ɪn pleɪs/ | 인플레이스 |
| stable/ˈsteɪbl/ | 안정성 |
| field/fiːld/ | A named component of a record, with its own value and type. |
| records | Groups of related data stored together as a single item. |
| linear time | Running time that grows in proportion to the number of items. |
의도적으로 느린 정렬
- Every serious library sorts with an algorithm no exam asks you to write. Bubble sort and insertion sort are both $O(n^2)$, and both are beaten by any decent sort on a large list.
- 그들은 anyway로 과목 과정에 포함되어 있으며 좋은 이유가 있습니다: 손으로 추적하기 충분히 짧으며, 하나를 추적하는 것이 정렬이 배열에 실제로 무엇을 하는지 배우는 방법입니다.
- There is also a real case for insertion sort. On a list that is small, or already nearly sorted, it is genuinely the fastest thing there is, and real libraries switch to it for exactly those cases.
- 이 수업은 버블 정렬과 삽입 정렬입니다: 알고리즘, 그들의 행동, 그리고 각각이 승리를 거두는 곳.
버블 정렬
FOR pass ← 1 TO n - 1
swapped ← FALSE
FOR i ← 1 TO n - pass
IF A[i] > A[i + 1] THEN
swap A[i], A[i + 1]
swapped ← TRUE
ENDIF
NEXT i
IF NOT swapped THEN // already sorted
EXIT FOR
ENDIF
NEXT pass
- 각 패스는 인접한 쌍(adjacent pairs) 을 비교하고 순서가 틀린 경우를 스왑하므로, 남은 최대 값이 끝으로 "부풀어 오릅니다(bubbles)."
- 패스 $k$ 후 마지막 $k$ 요소들은 최종화되었으며, 이것이 내부 루프가 $n - \text{pass}$에서 멈추는 이유입니다.
swapped플래그는 조기에 멈출 수 있게 합니다: 한 전체 패스에서 스왑이 없다면, 리스트는 이미 정렬된 것입니다.
삽입 정렬(Insertion Sort)
FOR i ← 2 TO n
key ← A[i]
j ← i - 1
WHILE j >= 1 AND A[j] > key DO
A[j + 1] ← A[j] // shift right
j ← j - 1
ENDWHILE
A[j + 1] ← key // drop it in
NEXT i
- 이는 앞쪽에 정렬된 섹션을 구축하며, 매번 하나씩 성장합니다. 각 새로운 요소는
key로 잠시 비워두고, 큰 요소들은 간극을 만들기 위해 오른쪽으로 이동되며, 키는 떨어집니다. - 이것이 사람들이 대부분 카드를 손에 쥐고 정렬하는 방식이며, 이것이 시험이 기대하는 유추입니다.

왼쪽은 정렬되고, 오른쪽은 건드리지 않으며, 경계선이 오른쪽으로 이동합니다

정렬 알고리즘
compare adjacent, swap if needed
Step through a bubble sort: each pass floats the largest value to the end.
Bubble sort works by:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Each pass swaps adjacent pairs, "bubbling" the largest element to the end.
The average/worst-case time complexity of bubble sort is:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Two nested loops over n elements give O(n²); the best case (already sorted) is O(n) with the early exit.
worked example: 한 pass를 추적하다
- 버블 정렬의 첫 pass를 5, 3, 8, 1에 대해 추적하십시오.
- 5와 3 비교: 순서 틀림, 스왑하여 3, 5, 8, 1. 5와 8 비교: 순서 맞음, 스왑 없음. 8과 1 비교: 스왗하여 3, 5, 1, 8.
- 한 패스 후 최대 값인 8이 최종 위치에 배치되었고, 이제부터 각 패스당 하나의 추가 비교는 생략할 수 있습니다.
- Now trace insertion sort's third step on 3, 5, 8, 1. The key is 1. Shift 8, 5 and 3 each one place right, then place 1 at the front: 1, 3, 5, 8. Show the array after every step; that is where the marks are.

Insertion sort builds the sorted result by:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
It grows a sorted prefix on the left, shifting larger elements right to drop each key into place.
How does insertion sort place each new element?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Holding the key aside and shifting is what distinguishes it from bubble sort's repeated adjacent swaps.
성능
| 버블 | 삽입 | |
|---|---|---|
| 최선(best case) | $O(n)$, 스왑 없는 한 패스 | $O(n)$, 이미 정렬되어 있어 이동(shift) 없음 |
| 평균 및 최악 | $O(n^2)$ | $O(n^2)$ |
| 추가 메모리 | $O(1)$, in place | $O(1)$, in place |
| 안정성(stable) | 예 | 예, 안정적(stable) |
- In place은 상수 수준의 추가 메모리만 필요하며 배열 자체 내에서 정렬함을 의미합니다. Stable은 두 등가 값이 원래의 상대적 순서를 유지함을 의미하며, 이는 리스트가 다른 필드에 의해 이미 정렬된 경우에 중요합니다.
- 둘 다 이미 정렬된 데이터에서 $O(n)$에 도달하지만, 버블 정렬이
swapped플래그를 가지고 있을 때만 그렇습니다. 없으면, 항상 모든 pass를 수행합니다.

After the first pass of a bubble sort on 5, 3, 8, 1, what is the array? Write the four numbers separated by commas.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
5 and 3 swap, 5 and 8 do not, 8 and 1 swap. The largest value has reached the end, so the next pass can be one comparison shorter.
worked example: 어떤 정렬인지, 그리고 왜
- 200,000레코드의 목록을 처음부터 정렬해야 합니다. neither: 둘 다 $O(n^2)$이므로, 병합 또는 퀵 정렬이 $O(n \log n)$이 필요합니다. Least bad를 선택하기보다 말하십시오.
- A sorted list of 10,000 gains 5 new records at the end and must be sorted again. Insertion sort: the data is nearly sorted, so each new key shifts only a short distance and it approaches $O(n)$.
- 교육적 예제는 종이에 손으로 추적되어야 합니다. 버블 정렬: 따라가기 가장 쉬우며, 이것이 그의 남은 실제 사용법입니다.
- 일반적인 선호도가 아닌 데이터 상태와 크기에서 근거를 제시하세요.

Match each sorting idea to what it means.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Bubble swaps neighbours, insertion grows a sorted prefix; both are O(n²) worst-case; stability is about equal-key order.
Insertion sort runs close to O(n) on small or nearly-sorted arrays, because few elements need to be shifted.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
On nearly-sorted data each new item is already almost in place — which is why insertion sort beats fancier sorts on small inputs.
Which are true of both bubble sort and insertion sort? Select 모든 that apply.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
On a large unsorted list an O(n log n) sort wins decisively. Saying so is the right answer, not choosing the least bad of the two.
이 카드는 내용이 수정되어 번역이 업데이트될 때까지 영어로 표시됩니다.
Why one pass is not the whole story
- Both sorts do repeated passes, and the exam distinguishes them by what one pass achieves and by when they stop.
- A bubble sort pass compares adjacent pairs and swaps them, so one pass carries the largest remaining item to its final place. The whole sort is $n - 1$ passes.
- An insertion sort 插入排序 pass takes the next item and moves it back into the already-sorted part, so after $k$ passes the first $k$ items are sorted among themselves but not yet in final position.
- Bubble sort can be improved with a flag: if a pass makes no swaps, the list is already sorted and the algorithm stops. This can reduce the number of passes on nearly-sorted data.
- Without the flag, both are $n^2$ in the worst case, which is why either is a poor choice for a large file and why the exam asks about small ones.
A sorted list of 10,000 records gains 5 new records at the end. Which sort suits re-sorting it?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Nearly sorted data is exactly insertion sort's best case, approaching O(n). Real libraries switch to it for this reason.
Match each sort to what one pass achieves.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
That difference is what a trace question is really testing. A bubble-sort flag also lets it stop early on nearly-sorted data, which insertion sort handles well anyway.
놓칠 수 있는 점
- 버블 정렬은 인접한 쌍을 비교합니다. 한 요소를 모든 다른 요소와 비교하는 답은 다른 알고리즘을 설명하는 것입니다.
- 내부 루프는 배열의 끝이 이미 고정되어 있으므로 각 passes마다 길이가 짧아집니다. 그 이유를 설명하십시오.
- 삽입 정렬은 공백을 만들기 위해 요소를 오른쪽으로 밀어내며, 반복적으로 스왑하지 않습니다. 이 차이가 바로 이 알고리즘의 핵심입니다.
- Both are $O(n^2)$ on average and at worst, and $O(n)$ at best. Give the case with the order.
이해했습니다
- 버블 정렬: 인접한 쌍을 반복적으로 비교하고 스왑하며, 가장 큰 요소가 끝으로 이동하고, 각 pass마다 내부 루프가 짧아지며, 조기 종료를 위한
swapped플래그가 있습니다. - 삽입 정렬: 앞쪽에서 정렬된 영역을 확장하며, 각 키를 잠시 제외해 두고, 더 큰 요소들을 오른쪽으로 밀어내어 키를 공백에 넣습니다.
- 둘 다 평균 및 최악의 경우 $O(n^2)$, 최상의 경우 $O(n)$이며, **in place(재배치)**이고 **안정적(stable)**입니다.
- 삽입 정렬은 작거나 거의 정렬된 목록에서 진정으로 우월합니다. 하지만 크고 무작위로 정렬되지 않은 목록에서는 어느 것이나 적절한 답이 아닙니다.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.