Skip to main content

Counting Sort

Definition​

Counting Sort is a non-comparative sorting algorithm that sorts elements by counting the number of occurrences of each unique element in the input array. It operates on integer arrays with a defined range of values

Practice​

counting_sort(arr[], size, max_val):
// Initialize count array with zeros
for i = 0 to max_val:
count[i] = 0

// Count occurrences of each element
for i = 0 to size:
count[arr[i]]++

// Modify count array to contain actual position
for i = 1 to max_val:
count[i] += count[i - 1]

// Build the sorted array
for i = size - 1 downto 0:
sorted[count[arr[i]] - 1] = arr[i]
count[arr[i]]--

// Copy sorted array to original array
for i = 0 to size:
arr[i] = sorted[i]