Counting Sort
Counting sort avoids comparisons. It counts how many times each key appears, then reconstructs the output in key order.
이 멘탈 모델부터 시작하세요
Counting sort avoids comparisons. It counts how many times each key appears, then reconstructs the output in key order.
불필요한 전문용어 없이 동작 방식 이해하기
It is powerful when keys are integers in a reasonably small range.
Its complexity depends on n plus the key range k, so a huge sparse range can make it wasteful.
알고리즘을 연속된 의사결정으로 읽기
Understand what one pass/partition/merge guarantees.
Track which region is already finalized.
Reason about comparisons, swaps/moves and extra memory.
Read a tiny input by hand and write down the state after every important operation. For Counting Sort, the goal is to make the invariant visible rather than to memorize code.
function countingSort(a, max = Math.max(...a)) {
const count = Array(max + 1).fill(0);
for (const x of a) count[x]++;
const out = [];
for (let value = 0; value < count.length; value++) {
for (let c = 0; c < count[value]; c++) out.push(value);
}
return out;
}문법을 외우지 마세요. 각 줄에서 바뀌는 상태를 따라가고 위에서 설명한 불변식과 연결하세요.
O(n + k)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
적합한 경우
- Choose based on input size, order, key range, stability and memory limits.
보통 어디에서 문제가 생기는가
- Comparing only average Big-O.
- Forgetting stability, in-place behavior, recursion depth or key-domain assumptions.
전문적인 답변 구조
Explain why it can beat the comparison-sorting lower bound: it uses assumptions about the key domain rather than only pairwise comparisons.
What problem does Counting Sort solve?
Counting sort avoids comparisons. It counts how many times each key appears, then reconstructs the output in key order.
복잡도에 대해 무엇을 언급해야 하나요?
Its typical cost here is O(n + k), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
가장 흔한 실수는 무엇인가요?
Comparing only average Big-O.