Count Sort Visualization

Speed:
Step: 0 / -1
Algorithm Code
1function countingSort(arr) {
2    // Find the maximum element in the array
3    const max = Math.max(...arr);
4    
5    // Create a count array to store the count of each element
6    const count = new Array(max + 1).fill(0);
7    
8    // Count the occurrences of each element in the input array
9    for (let i = 0; i < arr.length; i++) {
10      count[arr[i]]++;
11    }
12    
13    // Modify the count array to store the position of each element
14    for (let i = 1; i <= max; i++) {
15      count[i] += count[i - 1];
16    }
17    
18    // Create an output array to store the sorted elements
19    const output = new Array(arr.length);
20    
21    // Build the output array by placing elements at their correct positions
22    for (let i = arr.length - 1; i >= 0; i--) {
23      output[count[arr[i]] - 1] = arr[i];
24      count[arr[i]]--;
25    }
26    
27    // Copy the sorted elements back to the original array
28    for (let i = 0; i < arr.length; i++) {
29      arr[i] = output[i];
30    }
31    
32    return arr;
33  }
Visualization