Counting Sort
Last translate with upstream: 59c5913(Jul 20, 2021)
This article will briefly introduce counting sort.
Introduction¶
Counting sort is an algorithm with linear time complexity.
Principles¶
Counting sort works with an extra array
The counting sort consists of three steps:
- Count how many times each number appears.
- Find the prefix sum of the occurrence of each number.
- Using the prefix sum of the number of occurrences, calculate the ranking of each number from right to left.
Properties¶
Stability¶
Counting sort is a stable sorting algorithm.
Time Complexity¶
Time complexity of counting sort is
Code Implementations¶
Pseudocode¶
C++¶
// C++ Version
const int N = 100010;
const int W = 100010;
int n, w, a[N], cnt[W], b[N];
void counting_sort() {
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i <= n; ++i) ++cnt[a[i]];
for (int i = 1; i <= w; ++i) cnt[i] += cnt[i - 1];
for (int i = n; i >= 1; --i) b[cnt[a[i]]--] = a[i];
}
Python¶
# Python Version
N = W = 100010
n = w = 0
a = b = [0] * N
cnt = [0] * W
def counting_sort():
for i in range(1, n + 1):
cnt[a[i]] += 1
for i in range(1, w + 1):
cnt[i] += cnt[i - 1]
for i in range(n, 0, -1):
b[cnt[a[i]] - 1] = a[i]
cnt[a[i]] -= 1
References and Footnotes¶
buildLast update and/or translate time of this article,Check the history
editFound smelly bugs? Translation outdated? Wanna contribute with us? Edit this Page on Github
peopleContributor of this article OI-wiki
translateTranslator of this article Visit the original article!
copyrightThe article is available under CC BY-SA 4.0 & SATA ; additional terms may apply.