实现说明
整个示例围绕函数 counting_sort组织。
这个文件只在 for value in values 里循环。
使用要点
- 跑完文件,输出里会留下标记——
scores:、sorted:。 - 把
counting_sort当作 API:导入它,其余代码可以忽略。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 文件在加载时定义 counting_sort。
入口签名:def counting_sort(values, max_value)
代码示例
def counting_sort(values, max_value):
"""Sort small non-negative integers without any pairwise comparisons."""
# counts[v] = how many times v appeared: O(n + max_value) overall.
counts = [0] * (max_value + 1)
for value in values:
counts[value] += 1
# Replay each value count[v] times. Equal keys lose their original
# order, so this plain variant suits bare ints, not records.
sorted_values = []
for value, count in enumerate(counts):
sorted_values.extend([value] * count)
return sorted_values
scores = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print("scores:", scores)
print("sorted:", counting_sort(scores, 9))
ages = [0, 2, 2, 1, 0]
print("ages :", ages, "->", counting_sort(ages, 2))