---
id: wiki-2026-0508-bubble-sort
title: Bubble Sort
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [버블 정렬, Sinking Sort, Exchange Sort]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [algorithm, sorting, comparison-sort, education]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Python/C/Rust
  framework: stdlib
---

# Bubble Sort

## 매 한 줄
> **"매 인접 비교+swap 의 매 simplest sort"**. 1956 Iverson notation discussion 부터 매 textbook canonical example. 매 production 의 X — 매 O(n²) 이라 n>50 의 부적합. 매 2026 의 매 교육적 가치 + matrix-vector kernel optimization research 의 사용.

## 매 핵심

### 매 알고리즘
- 매 n-1 passes — 매 pass 마다 인접 두 원소 비교 + swap (잘못된 순서면).
- 매 pass 후 가장 큰 element 가 매 우측 끝 의 "bubble up".
- 매 in-place — O(1) extra space.
- 매 stable sort — 매 동등 키 의 상대적 순서 유지.

### 매 복잡도
- **Worst/Average**: O(n²) — 매 reverse-sorted input.
- **Best**: O(n) — 매 already-sorted + early-termination flag.
- **Comparisons**: n(n-1)/2 worst case.
- **Swaps**: 매 inversions 수 = n(n-1)/2 worst case.

### 매 응용
1. **Education**: 매 introductory CS course 의 1st sort.
2. **Tiny n (<10)**: 매 cache-friendly + low overhead.
3. **Nearly-sorted detection**: 매 single-pass 로 sorted 여부 check.

## 💻 패턴

### Classic Bubble Sort
```python
def bubble_sort(arr: list[int]) -> None:
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
```

### Optimized with Early-Exit Flag
```python
def bubble_sort_optimized(arr: list[int]) -> None:
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            return  # 매 already sorted — 매 O(n) best case
```

### Cocktail Shaker (Bidirectional)
```python
def cocktail_sort(arr: list[int]) -> None:
    lo, hi = 0, len(arr) - 1
    while lo < hi:
        for j in range(lo, hi):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
        hi -= 1
        for j in range(hi, lo, -1):
            if arr[j - 1] > arr[j]:
                arr[j - 1], arr[j] = arr[j], arr[j - 1]
        lo += 1
```

### Generic with Comparator (Rust)
```rust
fn bubble_sort<T, F: Fn(&T, &T) -> std::cmp::Ordering>(arr: &mut [T], cmp: F) {
    let n = arr.len();
    for i in 0..n.saturating_sub(1) {
        let mut swapped = false;
        for j in 0..n - 1 - i {
            if cmp(&arr[j], &arr[j + 1]) == std::cmp::Ordering::Greater {
                arr.swap(j, j + 1);
                swapped = true;
            }
        }
        if !swapped { return; }
    }
}
```

### Branchless Inner Loop (CPU pipeline-friendly)
```c
void bubble_sort_branchless(int *a, int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            int cmp = a[j] > a[j + 1];
            int tmp = a[j];
            a[j]     = cmp ? a[j + 1] : a[j];
            a[j + 1] = cmp ? tmp      : a[j + 1];
        }
    }
}
```

### Linked-List Variant
```python
def bubble_sort_linked(head):
    if not head: return head
    swapped = True
    while swapped:
        swapped = False
        cur = head
        while cur.next:
            if cur.val > cur.next.val:
                cur.val, cur.next.val = cur.next.val, cur.val
                swapped = True
            cur = cur.next
    return head
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| n < 10, simple code 우선 | Bubble Sort (optimized) |
| n < 50, 거의 sorted | Insertion Sort > Bubble |
| n > 100 | Quicksort/Timsort/std `sort` |
| Stable + small n | Bubble or Insertion |
| Production code | 매 절대 X — 매 stdlib `sort` |

**기본값**: 매 production 은 stdlib (Timsort/IntroSort) — 매 Bubble 은 교육 only.

## 🔗 Graph
- 부모: [[Sorting Algorithms]] · [[Comparison Sort]]
- 변형: [[Cocktail Shaker Sort]] · [[Odd-Even Sort]]
- 응용: [[Algorithm Education]] · [[Inversion Counting]]
- Adjacent: [[Insertion Sort]] · [[Selection Sort]] · [[Quicksort]] · [[Timsort]]

## 🤖 LLM 활용
**언제**: 매 algorithm tutorials 의 explanation, 매 n<20 의 quick prototype, 매 inversions counting heuristic.
**언제 X**: 매 production sort, 매 n>100, 매 latency-sensitive paths — 매 Timsort/Quicksort 의 사용.

## ❌ 안티패턴
- **Production deployment**: 매 100x slower than Timsort 의 large n.
- **Recursive bubble**: 매 stack overhead 의 점진적 추가 — 매 pure loss.
- **No early-exit**: 매 sorted input 의 O(n²) 의 낭비.
- **Bubble for objects with expensive comparison**: 매 n² comparisons 의 cost explosion.

## 🧪 검증 / 중복
- Verified (Knuth TAOCP Vol 3 §5.2.2, CLRS Ch. 2 problem 2-2).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Bubble sort patterns + variants + decision matrix |
