How it works
Counts occurrences of each value and uses arithmetic to place elements. Very fast when the range k is not much larger than n.
Implementation
function countingSort(arr, stats) { const n = arr.length; if (n < 1) return; let max = arr[0]; for (let i = 1; i < n; i++) max = Math.max(max, arr[i]); const count = new Array(max + 1).fill(0); for (let i = 0; i < n; i++) { count[arr[i]]++; compare(i, i); } let idx = 0; const sorted = new Set(); for (let v = 0; v <= max; v++) { for (let c = 0; c < count[v]; c++) { arr[idx] = v; write(idx, v); markSorted(idx); idx++; checkpoint(idx, n); } } }
def countingSort(arr, stats): if (n < 1): return max = arr[0] for i in range(1, n): max = (max if max >= arr[i] else arr[i]) count = [0] * (max + 1) for i in range(n): count[arr[i]] += 1 compare(i, i) idx = 0 sorted = set() for v in range((max + 1)): for c in range(count[v]): arr[idx] = v write(idx, v) markSorted(idx) idx += 1 checkpoint(idx, n)
#include <vector> #include <algorithm> void sort(std::vector<int>& arr, int n, int& comparisons, int& swaps) { if((n < 1)) { return; } int max = arr[0]; for(int i=1; i<n; i++) { max = ((max) > (arr[i]) ? (max) : (arr[i])); } std::vector<int> count((max + 1), 0); for(int i=0; i<n; i++) { count[arr[i]]++; compare(i, i); } int idx = 0; int sorted = 0; for(int v=0; v<(max + 1); v++) { for(int c=0; c<count[v]; c++) { arr[idx] = v; write(idx, v); markSorted(idx); idx++; checkpoint(idx, n); } } }
public void Sort(int[] arr, int n, dynamic stats) { if((n < 1)) { return; } int max = arr[0]; for(int i=1; i<n; i++) { max = Math.Max(max, arr[i]); } int[] count = new int[(max + 1)]; for(int i=0; i<n; i++) { count[arr[i]]++; compare(i, i); } int idx = 0; int sorted = 0; for(int v=0; v<(max + 1); v++) { for(int c=0; c<count[v]; c++) { arr[idx] = v; write(idx, v); markSorted(idx); idx++; checkpoint(idx, n); } } }
#include <stdio.h> #include <string.h> #include <stdlib.h> void sort(int arr[], int n, int* comparisons, int* swaps) { if((n < 1)) { return; } int max = arr[0]; for(int i=1; i<n; i++) { max = ((max) > (arr[i]) ? (max) : (arr[i])); } int* count = (int*)malloc(((max + 1)) * sizeof(int)); memset(count, 0, ((max + 1)) * sizeof(int)); for(int i=0; i<n; i++) { count[arr[i]]++; compare(i, i); } int idx = 0; int sorted = 0; for(int v=0; v<(max + 1); v++) { for(int c=0; c<count[v]; c++) { arr[idx] = v; write(idx, v); markSorted(idx); idx++; checkpoint(idx, n); } } }