Sorting

Counting Sort

Size:15
Execution Narrative
Step 1 of 50Start
Line 1
Starting Counting Sort on array of 15 elements.
Comparisons28
Swaps0
Operations28

Overview & Concept

Counting Sort is a non-comparison integer sorting algorithm that runs in linear O(n + k) time, where n is the number of elements and k is the range of key values. It works by counting the frequency of each distinct value, computing prefix sums to determine exact output positions, and placing elements directly into a sorted array.

How It Works

Frequency Counting: Tally occurrences of each integer in a count array of size k = max - min + 1.

Prefix Sum Accumulation: Transform count array so each index stores the cumulative total of smaller elements.

Right-to-Left Placement: Iterate through input backwards, placing elements at designated positions to guarantee stability.

Step-by-Step Execution

1. Find RangeDetermine minimum and maximum values to size the count array.
2. Count OccurrencesIterate input array and increment count[val - min].
3. Accumulate Prefix SumsUpdate count[i] = count[i] + count[i - 1].
4. Populate Output ArrayPlace elements into output array and decrement count to maintain stability.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n + k)O(n + k)O(n + k)O(n + k)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure countingSort(A):
  find min and max in A; range = max - min + 1
  count = array of zeros of size range
  for each x in A: count[x - min]++
  compute prefix sums in count array
  for i = n - 1 down to 0: // stable right-to-left
    place A[i] into output[--count[A[i] - min]]
  copy output array back to A
  return A
end procedure
Algorithmic Invariants
  • Frequency Invariant: The count array stores exact counts of every integer value in the input.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •Linear O(n + k) time: beats the theoretical O(n log n) comparison-based sorting limit.
  • •Stable sorting algorithm.

Trade-offs & Limitations

  • •Requires O(k) memory, which explodes if the range k is large relative to n.
  • •Only applicable to integer or discrete enumerable keys.

Real-World Applications

Subroutine for Radix Sort

Digit-by-digit stable counting sort in Radix Sort.

Categorical Data Sorting

Sorting exam scores, ages, or status codes within bounded small ranges.

Decision Guide: When to Use

Ideal Scenarios

  • ✓When sorting integer keys within a known, small range k (e.g. k ≤ O(n)).

Consider Alternatives When

  • ✕When values have a vast range (e.g. 32-bit arbitrary hashes) or floating-point numbers.

Compare trade-offs and complexity across complementary tools in AlgoViz.