Recent from talks
Contribute something
Nothing was collected or created yet.
Counting sort
View on Wikipedia| Class | Sorting Algorithm |
|---|---|
| Data structure | Array |
| Worst-case performance | , where k is the range of the non-negative key values. |
| Worst-case space complexity |
In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small positive integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that possess distinct key values, and applying prefix sum on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum key value and the minimum key value, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. It is often used as a subroutine in radix sort, another sorting algorithm, which can handle larger keys more efficiently.[1][2][3]
Counting sort is not a comparison sort; it uses key values as indexes into an array and the Ω(n log n) lower bound for comparison sorting will not apply.[1] Bucket sort may be used in lieu of counting sort, and entails a similar time analysis. However, compared to counting sort, bucket sort requires linked lists, dynamic arrays, or a large amount of pre-allocated memory to hold the sets of items within each bucket, whereas counting sort stores a single number (the count of items) per bucket.[4]
Input and output assumptions
[edit]In the most general case, the input to counting sort consists of a collection of n items, each of which has a non-negative integer key whose maximum value is at most k.[3] In some descriptions of counting sort, the input to be sorted is assumed to be more simply a sequence of integers itself,[1] but this simplification does not accommodate many applications of counting sort. For instance, when used as a subroutine in radix sort, the keys for each call to counting sort are individual digits of larger item keys; it would not suffice to return only a sorted list of the key digits, separated from the items.
In applications such as in radix sort, a bound on the maximum key value k will be known in advance, and can be assumed to be part of the input to the algorithm. However, if the value of k is not already known then it may be computed, as a first step, by an additional loop over the data to determine the maximum key value.
The output is an array of the elements ordered by their keys. Because of its application to radix sorting, counting sort must be a stable sort; that is, if two elements share the same key, their relative order in the output array and their relative order in the input array should match.[1][2]
Pseudocode
[edit]In pseudocode, the algorithm may be expressed as:
function CountingSort(input, k) is
count ← array of k + 1 zeros
output ← array of same length as input
for i = 0 to length(input) - 1 do
j = key(input[i])
count[j] = count[j] + 1
for i = 1 to k do
count[i] = count[i] + count[i - 1]
for i = length(input) - 1 down to 0 do
j = key(input[i])
count[j] = count[j] - 1
output[count[j]] = input[i]
return output
Where input is the array to be sorted, key returns the numeric key of each item in the input array, count is an auxiliary array used first to store the numbers of items with each key, and then (after the second loop) to store the positions where items with each key should be placed,
k is the maximum value of the non-negative key values and output is the sorted output array.
In summary, the algorithm loops over the items in the first loop, computing a histogram of the number of times each key occurs within the input collection. After that in the second loop, it performs a prefix sum computation on count in order to determine, for each key, the position range where the items having that key should be placed; i.e. items of key should be placed starting in position count[]. Finally, in the third loop, it loops over the items of input again, but in reverse order, moving each item into its sorted position in the output array.[1][2][3]
The relative order of items with equal keys is preserved here; i.e., this is a stable sort.
Complexity analysis
[edit]Because the algorithm uses only simple for loops, without recursion or subroutine calls, it is straightforward to analyze. The initialization of the count array, and the second for loop which performs a prefix sum on the count array, each iterate at most k + 1 times and therefore take O(k) time. The other two for loops, and the initialization of the output array, each take O(n) time. Therefore, the time for the whole algorithm is the sum of the times for these steps, O(n + k).[1][2]
Because it uses arrays of length k + 1 and n, the total space usage of the algorithm is also O(n + k).[1] For problem instances in which the maximum key value is significantly smaller than the number of items, counting sort can be highly space-efficient, as the only storage it uses other than its input and output arrays is the Count array which uses space O(k).[5]
Variant algorithms
[edit]If each item to be sorted is itself an integer, and used as key as well, then the second and third loops of counting sort can be combined; in the second loop, instead of computing the position where items with key i should be placed in the output, simply append Count[i] copies of the number i to the output.
This algorithm may also be used to eliminate duplicate keys, by replacing the Count array with a bit vector that stores a one for a key that is present in the input and a zero for a key that is not present. If additionally the items are the integer keys themselves, both second and third loops can be omitted entirely and the bit vector will itself serve as output, representing the values as offsets of the non-zero entries, added to the range's lowest value. Thus the keys are sorted and the duplicates are eliminated in this variant just by being placed into the bit array.
For data in which the maximum key size is significantly smaller than the number of data items, counting sort may be parallelized by splitting the input into subarrays of approximately equal size, processing each subarray in parallel to generate a separate count array for each subarray, and then merging the count arrays. When used as part of a parallel radix sort algorithm, the key size (base of the radix representation) should be chosen to match the size of the split subarrays.[6] The simplicity of the counting sort algorithm and its use of the easily parallelizable prefix sum primitive also make it usable in more fine-grained parallel algorithms.[7]
As described, counting sort is not an in-place algorithm; even disregarding the count array, it needs separate input and output arrays. It is possible to modify the algorithm so that it places the items into sorted order within the same array that was given to it as the input, using only the count array as auxiliary storage; however, the modified in-place version of counting sort is not stable.[3]
History
[edit]Although radix sorting itself dates back far longer, counting sort, and its application to radix sorting, were both invented by Harold H. Seward in 1954.[1][4][8]
References
[edit]- ^ a b c d e f g h Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001), "8.2 Counting Sort", Introduction to Algorithms (2nd ed.), MIT Press and McGraw-Hill, pp. 168–170, ISBN 0-262-03293-7. See also the historical notes on page 181.
- ^ a b c d Edmonds, Jeff (2008), "5.2 Counting Sort (a Stable Sort)", How to Think about Algorithms, Cambridge University Press, pp. 72–75, ISBN 978-0-521-84931-9.
- ^ a b c d Sedgewick, Robert (2003), "6.10 Key-Indexed Counting", Algorithms in Java, Parts 1-4: Fundamentals, Data Structures, Sorting, and Searching (3rd ed.), Addison-Wesley, pp. 312–314.
- ^ a b Knuth, D. E. (1998), The Art of Computer Programming, Volume 3: Sorting and Searching (2nd ed.), Addison-Wesley, ISBN 0-201-89685-0. Section 5.2, Sorting by counting, pp. 75–80, and historical notes, p. 170.
- ^ Burris, David S.; Schember, Kurt (1980), "Sorting sequential files with limited auxiliary storage", Proceedings of the 18th annual Southeast Regional Conference, New York, NY, USA: ACM, pp. 23–31, doi:10.1145/503838.503855, ISBN 0897910141, S2CID 5670614.
- ^ Zagha, Marco; Blelloch, Guy E. (1991), "Radix sort for vector multiprocessors", Proceedings of Supercomputing '91, November 18-22, 1991, Albuquerque, NM, USA, IEEE Computer Society / ACM, pp. 712–721, doi:10.1145/125826.126164, ISBN 0897914597.
- ^ Reif, John H. (1985), "An optimal parallel algorithm for integer sorting", Proc. 26th Annual Symposium on Foundations of Computer Science (FOCS 1985), pp. 496–504, doi:10.1109/SFCS.1985.9, ISBN 0-8186-0644-4, S2CID 5694693.
- ^ Seward, H. H. (1954), "2.4.6 Internal Sorting by Floating Digital Sort", Information sorting in the application of electronic digital computers to business operations (PDF), Master's thesis, Report R-232, Massachusetts Institute of Technology, Digital Computer Laboratory, pp. 25–28.
External links
[edit]- Counting Sort html5 visualization
- Demonstration applet from Cardiff University Archived 2013-06-02 at the Wayback Machine
- Kagel, Art S. (2 June 2006), "counting sort", in Black, Paul E. (ed.), Dictionary of Algorithms and Data Structures, U.S. National Institute of Standards and Technology, retrieved 2011-04-21.
Counting sort
View on GrokipediaFundamentals
Description
Counting sort is a non-comparative integer sorting algorithm that determines the sorted order of elements by first counting the occurrences of each possible value in the input and then using these counts, along with arithmetic operations, to directly compute and place each element in its final position in the output array.[3] This approach was originally described as a subroutine within digital sorting methods by Harold H. Seward in his 1954 master's thesis at MIT.[3] Unlike comparison-based algorithms that rely on pairwise element comparisons to establish order, counting sort leverages the discrete nature of the input values and a known bounded range, employing array indices directly corresponding to those values to avoid comparisons altogether.[1] It operates by initializing a count array sized to the input range, incrementing entries for each input value's frequency, and then transforming this into a cumulative distribution that specifies output positions.[1] As a distribution-based sorting method, counting sort partitions elements into temporary storage based on their values—effectively using the count array as a set of buckets—and reconstructs the sorted sequence by placing elements according to the cumulative counts, akin to a single-pass variant of the distribution step in radix sort.[1] This design enables efficient handling of discrete data when the value range is not excessively large, though it involves a space trade-off proportional to that range.[1]Assumptions
Counting sort requires a specific set of input conditions to function correctly and efficiently. The input is an array of elements, where each element is a non-negative integer with values ranging from 0 to , and represents the maximum value in the array, which must be known beforehand to determine the size of the auxiliary count array.[5] This known range allows for the allocation of a count array of size , enabling the algorithm to tally occurrences without exceeding memory bounds proportional to the input range.[6] The output of counting sort is a new array of the same size , containing the input elements rearranged in non-decreasing order. The assumption of non-negative integers is crucial because negative values would correspond to invalid negative indices in the count array, which are not supported in standard array implementations. Although adaptations exist—such as shifting all values by adding the absolute value of the minimum element to map them to a non-negative range—this approach deviates from the standard algorithm and can inflate the effective range , thereby reducing efficiency in both time and space when the input span is large.[7]The Algorithm
Pseudocode
Counting sort assumes the input consists of non-negative integers within a known range [0, k].[8] The following pseudocode describes the stable version of the algorithm, using zero-based indexing for arrays. It operates on an input array of length , producing a sorted output array of the same length, with a count array of size .[8][9]procedure countingSort(A[0..n-1], B[0..n-1], k)
C ← array of size (k + 1), initialized to 0 // Count occurrences of each value
for i ← 0 to n-1 do
C[A[i]] ← C[A[i]] + 1 // Increment count for A[i]
for j ← 1 to k do
C[j] ← C[j] + C[j-1] // Compute cumulative counts for placement positions
for i ← n-1 downto 0 do
B[C[A[i]] - 1] ← A[i] // Place A[i] at the correct position in B
C[A[i]] ← C[A[i]] - 1 // Decrement the count to handle multiples
procedure countingSort(A[0..n-1], B[0..n-1], k)
C ← array of size (k + 1), initialized to 0 // Count occurrences of each value
for i ← 0 to n-1 do
C[A[i]] ← C[A[i]] + 1 // Increment count for A[i]
for j ← 1 to k do
C[j] ← C[j] + C[j-1] // Compute cumulative counts for placement positions
for i ← n-1 downto 0 do
B[C[A[i]] - 1] ← A[i] // Place A[i] at the correct position in B
C[A[i]] ← C[A[i]] - 1 // Decrement the count to handle multiples
Step-by-Step Execution
To illustrate the execution of counting sort, consider an input array of length containing integers in the range to : . This example follows the standard stable implementation of the algorithm as described in introductory algorithms texts.[10] The process begins by initializing a count array of size (indices 0 to 5) to all zeros. Then, for each element in , the corresponding entry in is incremented to record the frequency of each value:| Value | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Count | 2 | 0 | 2 | 3 | 0 | 1 |
| Value | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Cumulative | 2 | 2 | 4 | 7 | 7 | 8 |
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=7&&&citation_type=wikipedia}} = 3, place 3 at position 6 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=3&&&citation_type=wikipedia}} to 6.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=6&&&citation_type=wikipedia}} = 0, place 0 at position 1 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=0&&&citation_type=wikipedia}} to 1.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=5&&&citation_type=wikipedia}} = 3, place 3 at position 5 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=3&&&citation_type=wikipedia}} to 5.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=4&&&citation_type=wikipedia}} = 2, place 2 at position 3 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=2&&&citation_type=wikipedia}} to 3.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=3&&&citation_type=wikipedia}} = 0, place 0 at position 0 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=0&&&citation_type=wikipedia}} to 0.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=2&&&citation_type=wikipedia}} = 3, place 3 at position 4 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=3&&&citation_type=wikipedia}} to 4.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=1&&&citation_type=wikipedia}} = 5, place 5 at position 7 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=5&&&citation_type=wikipedia}} to 7.
- For A{{grok:render&&&type=render_inline_citation&&&citation_id=0&&&citation_type=wikipedia}} = 2, place 2 at position 2 in , decrement C{{grok:render&&&type=render_inline_citation&&&citation_id=2&&&citation_type=wikipedia}} to 2.
Analysis
Time Complexity
The time complexity of counting sort is , where is the length of the input array and is the number of possible key values (i.e., one more than the difference between the maximum and minimum possible values in the input). This bound holds regardless of the input distribution, as the algorithm performs a fixed set of operations independent of the specific arrangement of elements.[1] The analysis breaks down as follows: the initial counting phase iterates over the input elements exactly once to tally occurrences in the auxiliary array, requiring time; the cumulative sum phase (or prefix sum computation for stable placement) iterates over the possible values in the auxiliary array, requiring time; and the output phase iterates over the input elements once more to construct the sorted array, again requiring time.[1] Initialization of the auxiliary array also takes time, which is subsumed in the overall term. More precisely, the exact running time can be expressed as , reflecting the linear traversal costs with lower-order terms for overhead. When , this simplifies to linear time , making counting sort particularly efficient for inputs with bounded integer keys.[1] As a non-comparison-based sorting algorithm, counting sort avoids the lower bound that applies to comparison sorts, enabling its linear performance in suitable scenarios.Space Complexity
The space complexity of counting sort is , where is the number of elements to sort and is the range of input values (specifically, the difference between the maximum and minimum keys plus one). This arises primarily from the count array, which requires space to tally frequencies of each possible key value, and the output array, which needs space to build the sorted result without overwriting the input.[1] More precisely, the total auxiliary space is given by , where the term captures minor overhead from temporary variables and indices.[1] A key trade-off occurs when , as the space then scales with , rendering counting sort inefficient or infeasible for datasets with expansive key ranges, such as when keys span up to or more.[1]Variants
Stable Variant
A stable sorting algorithm preserves the relative order of records with equal keys as they appear in the sorted output compared to the input.[11] The standard implementation of counting sort fills the output array by traversing the input from beginning to end using cumulative counts, which places earlier occurrences of equal keys toward the end of their group in the output, thereby reversing their relative order and making the sort unstable.[10] To ensure stability, the algorithm is modified to traverse the input array in reverse order during the placement phase, assigning positions such that earlier input elements with equal keys receive lower indices in the output.[9] This reverse traversal works because the cumulative count array tracks the rightmost available position for each key initially; processing later input elements first places them at higher indices within the key group, leaving lower indices for earlier elements encountered subsequently.[10] The pseudocode for the stable variant, adapted to zero-based indexing, highlights the backward loop:COUNTING-SORT(A, B, k)
1 let [count](/page/Count)[0..k] be a new array
2 for i ← 0 to k
3 [count](/page/Count)[i] ← 0
4 for j ← 0 to n - 1
5 [count](/page/Count)[A[j]] ← [count](/page/Count)[A[j]] + 1
6 for i ← 1 to k
7 [count](/page/Count)[i] ← [count](/page/Count)[i] + [count](/page/Count)[i - 1]
8 for j ← n - 1 downto 0
9 B[[count](/page/Count)[A[j]] - 1] ← A[j]
10 [count](/page/Count)[A[j]] ← [count](/page/Count)[A[j]] - 1
COUNTING-SORT(A, B, k)
1 let [count](/page/Count)[0..k] be a new array
2 for i ← 0 to k
3 [count](/page/Count)[i] ← 0
4 for j ← 0 to n - 1
5 [count](/page/Count)[A[j]] ← [count](/page/Count)[A[j]] + 1
6 for i ← 1 to k
7 [count](/page/Count)[i] ← [count](/page/Count)[i] + [count](/page/Count)[i - 1]
8 for j ← n - 1 downto 0
9 B[[count](/page/Count)[A[j]] - 1] ← A[j]
10 [count](/page/Count)[A[j]] ← [count](/page/Count)[A[j]] - 1
