정렬(Sort)이란 자료들을 일정한 순서대로 나열하는 것입니다. 컴퓨터 과학에서 가장 기본이 되는 알고리즘 중 하나입니다.
카드 게임을 할 때, 받은 카드를 손에 들고 작은 숫자부터 큰 숫자 순서로 정리하지 않나요? 이것이 바로 정렬입니다!
또 다른 예: 학교 출석부(학번 순), 사전(가나다 순), 칼 정리(크기 순)
| 알고리즘 | 방식 (쉬운 설명) | 성능 |
|---|---|---|
| 선택 정렬 | 제일 작은 것을 골라 앞으로 | O(n²) |
| 삽입 정렬 | 알맞은 자리에 끼워넣기 | O(n²) |
| 버블 정렬 | 옆끼리 비교해서 교환 | O(n²) |
| 퀵 정렬 | 반씩 나누어 정복 | O(n log n) |
Sorting is arranging data in a specific order. It is one of the most fundamental algorithms in computer science.
When playing card games, don't you arrange your cards from smallest to largest? That's exactly sorting!
More examples: school roster (by student ID), dictionary (alphabetical), organizing knives (by size)
| Algorithm | Method (Simple) | Performance |
|---|---|---|
| Selection Sort | Pick smallest, move to front | O(n²) |
| Insertion Sort | Insert at the right spot | O(n²) |
| Bubble Sort | Compare neighbors & swap | O(n²) |
| Quick Sort | Divide in half & conquer | O(n log n) |
선택 정렬(Selection Sort)은 배열에서 가장 작은 값을 선택하여 앞으로 보내는 과정을 반복합니다.
체육시간에 키 순서로 줄을 세울 때: ① 전체 중 키가 가장 작은 학생을 찾아서 맨 앞에 세우고 ② 나머지 중에서 또 가장 작은 학생을 찾아 두 번째에 세우고... 이걸 반복합니다. 이것이 선택 정렬입니다!
minIdx = 0 : "일단 [0]번이 제일 작다고 치자"if ary[minIdx] > ary[i] : "지금 최소보다 더 작은 값이 있니?"minIdx = i : "더 작은 걸 찾았으니 갱신!"Selection Sort repeatedly selects the smallest value from the array and moves it to the front.
During PE class, lining up by height: ① Find the shortest student and place them first ② Find the next shortest and place them second... Repeat. This is Selection Sort!
minIdx = 0 : "Let's assume [0] is the smallest"if ary[minIdx] > ary[i] : "Is there anything smaller?"minIdx = i : "Found something smaller, update!"추가 배열 없이, 원래 배열 안에서 최솟값을 찾아 현재 위치와 교환하는 방식입니다.
커피 컵(a)과 주스 컵(b)의 내용물을 바꾸려면? 빈 컵(tmp)이 하나 더 필요합니다!
Without an extra array, find the minimum and swap it with the current position within the original array.
To swap coffee cup (a) with juice cup (b)? You need an empty cup (tmp)!
정렬이 얼마나 느린지/빠른지를 판단하려면, "비교를 몇 번 하는가?"를 세면 됩니다.
학생 4명을 줄 세우는 건 쉽습니다. 하지만 1000명이라면? 비교 횟수가 기하급수적으로 늘어납니다!
To judge how slow/fast sorting is, count "how many comparisons?"
Lining up 4 students is easy. But 1000 students? The number of comparisons grows dramatically!
배열 [188, 162, 168, 120, 50, 150, 177, 105]를 선택 정렬로 오름차순 정렬하는 함수 selectionSort(ary)를 작성하시오. 배열 1개만 사용합니다.
배열에서 최댓값의 위치를 반환하는 함수 findMaxIdx(ary)를 작성하시오.
힌트: findMinIdx와 비교 조건(>)만 <로 바꾸면 됩니다!
> (더 작은 것 찾기), findMaxIdx는 < (더 큰 것 찾기)
Write a function selectionSort(ary) to sort [188, 162, 168, 120, 50, 150, 177, 105] ascending using only 1 array.
Write findMaxIdx(ary) that returns the maximum value's index.
Hint: Just change the comparison (>) to < in findMinIdx!
> (find smaller), findMaxIdx uses < (find larger)
삽입 정렬(Insertion Sort)은 기존 정렬된 데이터 중에서 자신의 위치를 찾아 삽입하는 방식입니다.
카드를 한 장씩 받을 때, 이미 손에 든 카드 사이에서 알맞은 자리를 찾아 끼워넣는 것과 같습니다. 예: 손에 [3, 7, 9]가 있고 5를 받으면 → [3, 5, 7, 9] 사이에 넣습니다.
break를 쓰는 이유: 처음 만난 큰 값 위치만 알면 됨findIdx == -1: 배열 전체에서 나보다 큰 값이 없음 = 내가 제일 큼 → 맨 뒤에
Insertion Sort works by finding the right position in already-sorted data and inserting the element there.
When receiving cards one by one, you find the right spot among cards already in hand and slide it in. e.g.: Hand has [3, 7, 9], receive 5 → [3, 5, 7, 9]
break is used because we only need the first larger value's positionfindIdx == -1: no larger value in array = I'm the largest → go to end
원본 배열에서 하나씩 꺼내어 새 배열의 올바른 위치에 insert()합니다.
배열 하나에서 뒤쪽 원소를 앞과 비교하며, 작으면 교환, 크면 정지합니다.
이미 정렬된 앞부분에 새 카드를 끼워넣는 것입니다. 뒤에서 앞으로 한 칸씩 비교하면서 자기 자리를 찾아갑니다.
range(end, 0, -1) : end에서 1까지 뒤로 이동ary[cur-1] > ary[cur] : "앞이 나보다 크면 교환"Take one element at a time from original and insert() at the correct position in a new array.
Within a single array, compare backwards: swap if smaller, stop if larger.
It's like inserting a new card into already-sorted cards. Compare backwards one step at a time to find your spot.
range(end, 0, -1) : move from end to 1 backwardsary[cur-1] > ary[cur] : "if previous is bigger than me, swap"| 구분 | 선택 정렬 | 삽입 정렬 |
|---|---|---|
| 비유 | 가장 작은 걸 골라 앞에 놓기 | 카드처럼 자리를 찾아 끼우기 |
| 방식 | 최솟값을 찾아 교환 | 올바른 위치에 삽입 |
| 시간 복잡도 | O(n²) 항상 | O(n²) 최악 / O(n) 최선 |
| 공간 | In-place O(1) | In-place O(1) |
| 안정성 | 불안정 | 안정 |
| 장점 | 구현 간단, 교환 적음 | 거의 정렬된 데이터에 빠름 |
| 비교 방향 | 앞 → 뒤 (전체 탐색) | 뒤 → 앞 (필요시만) |
· 데이터가 거의 정렬됨 → 삽입 정렬 (빠름!)
· 데이터가 완전 뒤죽박죽 → 둘 다 비슷하게 느림
· 아주 큰 데이터 → 둘 다 X → 퀵 정렬이나 병합 정렬 사용
ary[minIdx] > ary[k] (작은 것 먼저)ary[minIdx] < ary[k] (큰 것 먼저)
| Aspect | Selection Sort | Insertion Sort |
|---|---|---|
| Analogy | Pick smallest, place front | Find spot like cards |
| Method | Find min & swap | Insert at right position |
| Time | O(n²) always | O(n²) worst / O(n) best |
| Space | In-place O(1) | In-place O(1) |
| Stability | Unstable | Stable |
| Strength | Simple, fewer swaps | Fast on nearly-sorted |
| Direction | Front → Back (full scan) | Back → Front (as needed) |
· Data nearly sorted → Insertion Sort (fast!)
· Data completely random → both equally slow
· Very large data → neither → use Quick/Merge Sort
ary[minIdx] > ary[k] (smallest first)ary[minIdx] < ary[k] (largest first)
삽입 위치를 찾는 함수 findInsertIdx()를 사용하여 배열을 오름차순 정렬하는 프로그램을 작성하시오.
랜덤 10개 데이터를 내림차순으로 삽입 정렬하시오.
힌트: 비교 조건 >를 <로 바꾸면 내림차순!
Write a program using findInsertIdx() to sort an array in ascending order.
Sort 10 random numbers in descending order.
Hint: Change > to < for descending!
평균값(Mean)은 전체를 합산 후 개수로 나눈 값이고, 중앙값(Median)은 정렬 후 가운데 위치한 값입니다.
10명의 용돈: [7, 5, 11, 6, 9, 80000, 10, 6, 15, 12]
한 명이 부잣집 아이라 용돈이 80,000원입니다.
· 평균값 = (7+5+11+...+80000)/10 = 약 8,008원
→ 실제로 대부분 친구의 용돈은 10원 내외인데, 평균은 8,008? 비현실적!
· 중앙값 = 정렬 후 가운데 값 = 9원
→ 실제 대부분의 용돈 수준을 잘 반영합니다!
len(ary) // 2ary[len(ary)//2] — 딱 두 단계!
Mean is the sum divided by count; Median is the middle value after sorting.
10 students' allowances: [7, 5, 11, 6, 9, 80000, 10, 6, 15, 12]
One rich kid gets 80,000 allowance.
· Mean = (7+5+11+...+80000)/10 = ~8,008
→ Most get ~10, but mean says 8,008? Unrealistic!
· Median = middle value after sorting = 9
→ Better reflects actual allowance levels!
len(ary) // 2ary[len(ary)//2] — just two steps!
os.walk()로 폴더의 파일 목록을 추출한 뒤, 삽입 정렬로 역순(내림차순) 정렬합니다.
ary[cur-1] > ary[cur]ary[cur-1] < ary[cur]
성적으로 정렬 후, 상위-하위 학생을 짝지어 균형 잡힌 조를 만듭니다.
정렬 후 [영웅67, 화사71, 영탁78, 선미88, 민호92, 초아99]
→ 최하위-최상위 짝짓기:
· 영웅(67) + 초아(99) = 조 1
· 화사(71) + 민호(92) = 조 2
· 영탁(78) + 선미(88) = 조 3
→ 각 조 합계: 166, 163, 166 → 균형!
ary[cur-1][1] — 2차원 배열에서 [1]번(점수)을 기준으로 비교합니다. [0]은 이름입니다.
Extract file list with os.walk(), sort reverse (descending).
ary[cur-1] > ary[cur]ary[cur-1] < ary[cur]
Sort by score, pair top-bottom for balanced groups.
After sort: [Youngwoong 67, Hwasa 71, Youngtak 78, Sunmi 88, Minho 92, Choa 99]
→ Pair lowest-highest:
· Youngwoong(67) + Choa(99) = Group 1
· Hwasa(71) + Minho(92) = Group 2
· Youngtak(78) + Sunmi(88) = Group 3
→ Sums: 166, 163, 166 → Balanced!
ary[cur-1][1] — compares by [1] (score) in a 2D array. [0] is the name.
2차원 배열은 바로 정렬할 수 없으므로, 1차원으로 펼친 뒤 정렬하고 중앙값을 구합니다.
학생들이 4×4 (행×열)로 앉아 있는데, 키 순서로 줄을 세우려면? → 먼저 한 줄로 서게 해야 합니다! 이것이 "2차원 → 1차원 변환(flatten)"입니다.
2D arrays can't be sorted directly, so flatten to 1D first, sort, then find median.
Students sitting in 4×4 grid — to line up by height, they must first form a single line! This is "2D → 1D flatten".
학생 이름과 성적이 담긴 2차원 배열을 성적 기준으로 정렬한 뒤, 최하위-최상위 학생을 짝지어 조를 편성하는 프로그램을 작성하시오.
4×4 2차원 배열을 1차원으로 변환한 뒤, 선택 정렬하고 중앙값을 출력하는 프로그램을 작성하시오.
Sort a 2D array of [name, score] by score, then pair lowest with highest to create balanced groups.
Flatten a 4×4 2D array to 1D, sort with selection sort, and print the median.