pygorithm/sort/counting_sort.py

28 lines
945 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
计数排序:
1. 遍历数组,找出其中的最大数字,记为 m然后创建一个长度为 m+1 的辅助数组 counter 。
2. 借助 counter 统计 nums 中各数字的出现次数,其中 counter[num] 对应数字 num 的出现次数。
3. 统计方法很简单,只需遍历 nums设当前数字为 num每轮将 counter[num] 增加 1 即可。
4. 由于 counter 的各个索引天然有序,因此相当于所有数字已经排序好了。接下来,我们遍历 counter ,根据各数字出现次数从小到大的顺序填入 nums 即可。
"""
def counting_sort(nums: list[int]):
m = max(nums)
counter = [0] * (m + 1)
for num in nums:
counter[num] += 1
i = 0
for index, value in enumerate(counter):
if value > 0:
for j in range(value):
nums[i] = index
i += 1
nums = [54, 32, 99, 18, 75, 31, ]
counting_sort(nums)
print(nums)