[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+193 -61
View File
@@ -2,95 +2,227 @@
id: wiki-2026-0508-binary-search
title: Binary Search
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-BISE-001]
aliases: [이진 탐색, bisect, divide and conquer search, lower bound, upper bound, git bisect]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [auto-reinforced, binary-Search, algorithms, Optimization, Efficiency, log-time]
confidence_score: 0.97
verification_status: applied
tags: [algorithm, search, divide-conquer, log-n, bisection, git-bisect, parametric-search]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: any
framework: standard library
---
# [[Binary-Search|Binary-Search]]
# Binary Search
## 📌 한 줄 통찰 (The Karpathy Summary)
> "반으로 쪼개는 마법: 이미 정렬된 데이터더미 속에서 목표를 찾을 때, 매번 탐색 범위를 절반씩 과감히 날려버림으로써 수만 개의 데이터도 단 몇 번의 질문만으로 찾아내는 효율성의 극치."
## 📌 한 줄 통찰
> **"매 절반씩 의 탐색"**. 매 sorted array 의 매 O(log N). 매 100만 = 매 20 step. 매 algorithm 의 elegance 의 가장. 매 git bisect / parametric search / boundary find 의 same 원리.
## 📖 구조화된 지식 (Synthesized Content)
이진 탐색(Binary-Search)은 정렬된 배열에서 타겟 데이터를 찾는 고효율 탐색 알고리즘입니다.
## 📖 핵심
1. **알고리즘 순서**:
* 리스트의 중간값(Mid)을 선택.
* 중간값이 타겟보다 크면 왼쪽 절반 선택, 작으면 오른쪽 절반 선택.
* 범위가 1개가 남을 때까지 반복.
2. **복잡도**:
* **Time Complexity**: $O(log N)$ (데이터가 100만 개라도 단 20번의 비교로 해결).
* **Constraint**: 반드시 데이터가 **정렬(Sorted)**되어 있어야 함.
3. **응용**:
* 버그 수정 중 어떤 커밋에서 문제가 생겼는지 찾는 `git bisect`.
* 수학적 근사치를 구하는 이분법(Bisection method).
### 매 algorithm
1. 매 mid = (lo + hi) / 2.
2. 매 target == mid → return.
3. 매 target < mid → hi = mid - 1.
4. 매 target > mid → lo = mid + 1.
5. 매 lo > hi → not found.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 단순히 '데이터 찾기' 정책이었으나, 현대의 AI 시스템 정책은 하이퍼파라미터의 최적 범위를 좁히거나, 대규모 벡터 검색 엔진의 초기 검색 정책(Indexing)에서 이진 탐색의 수학적 원리를 응용함(RL Update).
- **정책 변화(RL Update)**: 엔지비니어링 면접 정책에서, 단순 암기 위주의 알고리즘 정책에서 탈피하여 이진 탐색의 원리를 응용해 복잡한 시스템 최적화 문제를 해결하는 '사고력 중심 평가 정책'으로 변모함.
### 매 complexity
- **Time**: O(log N). 매 100만 = 20 comparison.
- **Space**: O(1) iterative / O(log N) recursive.
- **Precondition**: 매 sorted (or monotonic predicate).
## 🔗 지식 연결 (Graph)
- [[BFS vs DFS|BFS vs DFS]], [[Search-Optimization|Search-Optimization]], [[Analysis|Analysis]], Pattern Recognition, [[Technical-Architecture|Technical-Architecture]]
- **Modern Tech/Tools**: `git bisect`, Database indexing, Standard library find functions.
---
### 매 variant
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
#### Lower bound (first ≥ target)
- 매 첫 매 element ≥ target.
**언제 이 지식을 쓰는가:**
- *(TODO)*
#### Upper bound (first > target)
- 매 첫 매 element > target.
**언제 쓰면 안 되는가:**
- *(TODO)*
#### Range [first, last]
- 매 lower / upper 의 결합.
## 🧪 검증 상태 (Validation)
#### Bisection on continuous
- 매 root finding (math).
- 매 epsilon-based termination.
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### Parametric search
- 매 monotonic predicate 의 boundary.
- 매 "최대 X 의 Y 의 OK" 의 search.
## 🧬 중복 검사 (Duplicate Check)
#### Galloping (exponential + binary)
- 매 unbounded 의 매 growing range 의 binary.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### 매 trap
- **Overflow**: `(lo + hi) / 2` 의 int overflow → `lo + (hi - lo) / 2`.
- **Off-by-one**: lo / hi / mid 의 boundary.
- **Infinite loop**: 매 mid 의 적절한 update.
- **Sorted assumption**: 매 unsorted 의 fail.
- **Float precision**: 매 epsilon 의 fix.
## 🕓 변경 이력 (Changelog)
### 매 응용
1. **`bisect` module** (Python).
2. **`std::lower_bound`** (C++).
3. **DB index** (B-tree): 매 internal node search.
4. **`git bisect`**: 매 commit 의 first bad.
5. **Parametric** (LeetCode): "min capacity for delivery in D days".
6. **Hyperparameter tune**: 매 LR sweep.
7. **Quantile estimate**: 매 streaming.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 매 modern variant
- **Branchless binary search**: 매 conditional move.
- **Eytzinger layout**: 매 cache-friendly.
- **Interpolation search**: 매 uniform 의 O(log log N).
- **Fractional cascading**: 매 multi-list.
## 💻 코드 패턴 (Code Patterns)
## 💻 패턴
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Classic (iterative)
```python
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target: return mid
if arr[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
```
## 🤔 의사결정 기준 (Decision Criteria)
### Lower bound (first ≥)
```python
def lower_bound(arr, target):
lo, hi = 0, len(arr)
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target: lo = mid + 1
else: hi = mid
return lo # 매 insertion point
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Python `bisect`
```python
import bisect
arr = [1, 3, 5, 7, 9]
bisect.bisect_left(arr, 5) # 2
bisect.bisect_right(arr, 5) # 3
bisect.insort(arr, 6) # 매 maintain sorted
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Parametric search ("min eat speed")
```python
def min_eating_speed(piles, h):
def can_eat(k):
return sum((p + k - 1) // k for p in piles) <= h
lo, hi = 1, max(piles)
while lo < hi:
mid = lo + (hi - lo) // 2
if can_eat(mid): hi = mid
else: lo = mid + 1
return lo
```
**기본값:**
> *(TODO)*
→ 매 monotonic predicate 의 boundary.
## ❌ 안티패턴 (Anti-Patterns)
### Bisection on float (root)
```python
def find_root(f, lo, hi, eps=1e-9):
while hi - lo > eps:
mid = (lo + hi) / 2
if f(mid) * f(lo) < 0: hi = mid
else: lo = mid
return (lo + hi) / 2
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
# sqrt(2) 의 root of x² - 2 = 0
result = find_root(lambda x: x*x - 2, 0, 2)
# 1.414213562373...
```
### `git bisect` (CLI)
```bash
git bisect start
git bisect bad HEAD
git bisect good v1.0
# 매 매 step 의 매 commit 의 test
git bisect good # or 'bad'
# 매 log N step → 매 first bad commit
git bisect reset
```
→ 매 1000 commit 의 매 10 step 의 culprit 의 find.
### Galloping (exponential + binary)
```python
def galloping_search(arr, target):
if arr[0] == target: return 0
bound = 1
while bound < len(arr) and arr[bound] < target:
bound *= 2
lo = bound // 2
hi = min(bound, len(arr) - 1)
return binary_search_range(arr, target, lo, hi)
```
→ 매 unbounded / online stream 의 OK.
### Eytzinger layout (cache-friendly)
```python
def eytzinger_search(arr, target):
"""매 BFS layout — 매 cache miss 매 minimize."""
n = len(arr)
k = 1
while k <= n:
if arr[k-1] < target: k = 2*k + 1
elif arr[k-1] > target: k = 2*k
else: return k - 1
return -1
```
## 🤔 결정 기준
| 상황 | 사용 |
|---|---|
| Sorted array search | binary search |
| Sorted insert | bisect.insort |
| Predicate boundary | parametric search |
| Float root | bisection method |
| Commit debugging | git bisect |
| Streaming quantile | binary search + treap |
| Cache-critical | Eytzinger layout |
**기본값**: Python `bisect` / C++ `lower_bound` 사용. 매 직접 구현 X.
## 🔗 Graph
- 부모: [[Algorithms]] · [[Search]] · [[Divide-and-Conquer]]
- 변형: [[Lower-Bound]] · [[Upper-Bound]] · [[Parametric-Search]] · [[Bisection-Method]] · [[Interpolation-Search]]
- 응용: [[Git-Bisect]] · [[B-Tree]] · [[Quantile-Estimation]] · [[Sorting]]
- Adjacent: [[Galloping-Search]] · [[Fractional-Cascading]] · [[Eytzinger-Layout]]
## 🤖 LLM 활용
**언제**: 매 sorted data search. 매 monotonic boundary. 매 root finding. 매 commit debugging.
**언제 X**: 매 unsorted (sort 의 cost X). 매 small N (linear OK). 매 non-monotonic.
## ❌ 안티패턴
- **`(lo + hi) / 2` overflow**: 매 large array 의 fail.
- **Sorted assumption 위반**: 매 wrong result.
- **`while lo < hi` vs `<=` 의 confusion**: 매 off-by-one.
- **Float epsilon 무시**: 매 무한 loop.
- **Library 무시 + 직접 구현**: 매 bug.
- **Linear search 의 substitute (small N)**: 매 over-engineering.
## 🧪 검증 / 중복
- Verified (CLRS, Knuth TAOCP, classic).
- 신뢰도 A.
- Related: [[Sorting]] · [[Divide-and-Conquer]] · [[Git-Bisect]] · [[B-Tree]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — variant + parametric + 매 git bisect + 매 Eytzinger + code |