Andrew Attilio | November 10, 2024

Counting Sort

Counting sort uses some assumptions:

  • Assume the input array contains nn non-negative integers.
  • Assume that each element aAa \in A is in the range 0 to kk, for some integer kk.

Example

Suppose A=[1,3,4,0,2,2,3]A = [1, 3, 4, 0, 2, 2, 3]. This implies that k4k \geq 4, where the most efficient choice of kk is 4.

We work with 3 arrays:

  • An input array A
  • An output array B
  • A temporary array C

We initialize CC to be of length kk. We begin the algorithm by counting the number of elements for all i{0,1,,k}i \in \{0, 1, \dots, k\}. We assign each C[i]C[i] to be the number of times that ii appears in AA.