Skip to content

Commit 5d400b7

Browse files
Merge pull request wangzheng0822#87 from jerryderry/counting-sort-python
Counting sort python
2 parents b97510d + a0267bf commit 5d400b7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

python/14_sorts/counting_sort.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
计数排序
3+
4+
Author: Wenru
5+
"""
6+
7+
from typing import List
8+
import itertools
9+
10+
def counting_sort(a: List[int]):
11+
if len(a) <= 1: return
12+
13+
# a中有counts[i]个数不大于i
14+
counts = [0] * (max(a) + 1)
15+
for num in a:
16+
counts[num] += 1
17+
counts = list(itertools.accumulate(counts))
18+
19+
# 临时数组,储存排序之后的结果
20+
a_sorted = [0] * len(a)
21+
for num in reversed(a):
22+
index = counts[num] - 1
23+
a_sorted[index] = num
24+
counts[num] -= 1
25+
26+
a = a_sorted
27+
28+
29+
if __name__ == "__main__":
30+
a1 = [1, 2, 3, 4]
31+
counting_sort(a1)
32+
print(a1)
33+
34+
a2 = [1, 1, 1, 1]
35+
counting_sort(a2)
36+
print(a2)
37+
38+
a3 = [4, 5, 0, 9, 3, 3, 1, 9, 8, 7]
39+
counting_sort(a3)
40+
print(a3)

0 commit comments

Comments
 (0)