Counting Sort
A non-comparison integer sorting algorithm that counts the occurrences of each value, computes cumulative counts, then reconstructs the sorted array.
Algorithm Information
Time Complexity
Best:
O(n + k)Average:
O(n + k)Worst:
O(n + k)Space Complexity
O(n + k)Properties
• Non-comparison based
• Stable sorting
• Linear time for bounded range
• Not in-place (uses extra memory)
1/118
Speed: 1x
Algorithm Code
1function countingSort(arr) {2 const n = arr.length;3 const max = Math.max(...arr);4 5 // Create count array of size max + 16 const count = new Array(max + 1).fill(0);7 8 // Count occurrences of each value9 for (let i = 0; i < n; i++) {10 count[arr[i]]++;11 }12 13 // Build cumulative counts14 for (let i = 1; i <= max; i++) {15 count[i] += count[i - 1];16 }17 18 // Build output array (iterate backwards for stability)19 const output = new Array(n);20 for (let i = n - 1; i >= 0; i--) {21 output[count[arr[i]] - 1] = arr[i];22 count[arr[i]]--;23 }24 25 // Copy output back to arr26 for (let i = 0; i < n; i++) {27 arr[i] = output[i];28 }29 30 return arr;31}Variable State
i:0
n:7
max:90
count:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
phase:init
Call Stack
countingSort
Array Visualization
Watch how Counting Sort processes the array step by step
640
341
252
123
224
115
906
Statistics
Comparisons0
Swaps0
Step1 / 118
Legend
Comparing
Active / Swapping
Sorted
Unsorted
Starting Counting Sort algorithm
How Counting Sort Works
Learn the fundamentals of counting sort through step-by-step explanations, code examples, and key concepts.