Counting Sort
A non-comparison based integer sorting algorithm that operates by counting the number of objects having distinct key values, then calculating the position of each object in the output sequence. It's efficient when the range of input data (k) is not significantly greater than the number of objects to be sorted (n).
Visualization
Interactive visualization for Counting Sort
Counting Sort Visualization
Interactive visualization with step-by-step execution
Implementation
1function countingSort(arr: number[]): number[] {
2 if (arr.length === 0) return [];
3
4 const max = Math.max(...arr);
5 const min = Math.min(...arr);
6 const range = max - min + 1;
7 const count = new Array(range).fill(0);
8 const output = new Array(arr.length);
9
10 // Count occurrences
11 for (const num of arr) {
12 count[num - min]++;
13 }
14
15 // Calculate cumulative count
16 for (let i = 1; i < count.length; i++) {
17 count[i] += count[i - 1];
18 }
19
20 // Build output array
21 for (let i = arr.length - 1; i >= 0; i--) {
22 output[count[arr[i] - min] - 1] = arr[i];
23 count[arr[i] - min]--;
24 }
25
26 return output;
27}Deep Dive
Theoretical Foundation
Counting sort works by counting the occurrences of each unique element in the input array and using this information to determine the position of each element in the sorted output. It's particularly efficient when the range of input values is small compared to the number of elements.
Complexity
Time
O(n + k)
O(n + k)
O(n + k)
Space
O(n + k)
Applications
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.