Counting Sort
Note
This page introduces Counting Sort, not Radix Sort.
This page briefly introduces Counting Sort.
Definition
Counting sort (English: Counting sort) is a linear-time sorting algorithm.
Process
Counting sort works by using an auxiliary array \(C\), where the \(i\)-th element is the number of elements in the input array \(A\) whose value equals \(i\). Then, based on array \(C\), the elements in \(A\) are placed in the correct positions.1
Its process is divided into three steps:
- Count the frequency of each number;
- Compute the prefix sum of the frequencies;
- Use the prefix sum of frequencies to determine the rank of each number from right to left.
Reason for Computing Prefix Sum
Directly placing elements from \(C\) into \(A\) in order of positive values cannot handle duplicate elements.
By computing the prefix sum for each entry in the auxiliary array \(C\), combined with the value of each entry, we can assign a unique rank to duplicate elements:
The value of each entry in the auxiliary array \(C\) is the count of duplicate elements for that key, and the prefix sum of that entry is the rank of the last duplicate element.
If we process \(A\) in reverse order, the sorted array will preserve the original order of \(A\) (for identical key values), resulting in a stable sorting algorithm.
Properties
Stability
Counting sort is a stable sorting algorithm.
Time Complexity
The time complexity of counting sort is \(O(n+w)\), where \(w\) represents the range of values in the input data.
Code Implementation
Pseudocode
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 | |
References and Notes
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用