| | | | | |

Counting Sort

void counting_sort(A,B,k)
// Pre:  A,B are arrays of type unsigned int
//       A,B are defined in the range [0,n)
//       A has values in the range [0,k)
// Post: A is unchanged
//       B is a stable sorted permutation of A
{
  unsigned int C [k];
  size_t i, j;
  for (i = 0; i < k; ++i)     // loop 1
    C[i] = 0;
  for (j = 0; j < n; ++j)     // loop 2
    ++C[A[j]];
  for (i = 1; i < k; ++i)     // loop 3
    C[i] = C[i] + C[i-1];
  for (j = n; j > 0; --j)     // loop 4
  {
    B[C[A[j-1]] - 1] = A[j-1];
    --C[A[j-1]];
  }
}

Recommended video: UCB Sorts 5


| | Top of Page | 8. Sorting Algorithms - 14 of 16