algoalgo-world
algoalgo-world/sort/counting-sort
sort/counting-sort

Counting Sort

best
O(n + k)
average
O(n + k)
worst
O(n + k)
space
O(n + k)
stability
stable
method
distribution

k is the value range

pick a language to open the code

def counting_sort(a):
    if not a:
        return
    count = [0] * (max(a) + 1)
    for value in a:
        count[value] += 1
    i = 0
    for value, times in enumerate(count):
        for _ in range(times):
            a[i] = value
            i += 1
function countingSort(a) {
  if (a.length === 0) return;
  const count = new Array(Math.max(...a) + 1).fill(0);
  for (const value of a) count[value]++;
  let i = 0;
  for (let value = 0; value < count.length; value++) {
    for (let k = 0; k < count[value]; k++) a[i++] = value;
  }
}
void counting_sort(int a[], int n, int top) {
    int* count = calloc(top + 1, sizeof(int));
    for (int i = 0; i < n; i++) count[a[i]]++;
    int i = 0;
    for (int value = 0; value <= top; value++) {
        for (int k = 0; k < count[value]; k++) a[i++] = value;
    }
    free(count);
}
void counting_sort(std::vector<int>& a) {
    if (a.empty()) return;
    int top = *std::max_element(a.begin(), a.end());
    std::vector<int> count(top + 1, 0);
    for (int value : a) count[value]++;
    size_t i = 0;
    for (int value = 0; value <= top; value++) {
        for (int k = 0; k < count[value]; k++) a[i++] = value;
    }
}
static void CountingSort(int[] a) {
    if (a.Length == 0) return;
    int top = a.Max();
    int[] count = new int[top + 1];
    foreach (int value in a) count[value]++;
    int i = 0;
    for (int value = 0; value <= top; value++) {
        for (int k = 0; k < count[value]; k++) a[i++] = value;
    }
}
static void countingSort(int[] a) {
    if (a.length == 0) return;
    int top = Arrays.stream(a).max().getAsInt();
    int[] count = new int[top + 1];
    for (int value : a) count[value]++;
    int i = 0;
    for (int value = 0; value <= top; value++) {
        for (int k = 0; k < count[value]; k++) a[i++] = value;
    }
}
watch it run, then read it