新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python計數(shù)排序法是什么
概念

1、計數(shù)排序的主要思想是將待排序數(shù)據(jù)值轉(zhuǎn)化為鍵,存儲在額外開辟的數(shù)組空間中。
2、計數(shù)排序要求輸入的數(shù)據(jù)必須是有確定范圍的整數(shù),因此計數(shù)排序法適用于量大范圍小的數(shù)據(jù)。
實例
def count_sort(data, maxValue): # 定義計數(shù)排序,data是列表數(shù)據(jù),maxValue表示值
bucket_len = maxValue + 1 # 定義桶的長度是值加1,桶號從0開始
bucket = [0] * bucket_len # 初始化桶
count = 0 # 計數(shù)個數(shù)
arr_len = len(data) # 列表長度
for i in range(arr_len): # 遍歷列表
if not bucket[data[i]]: # 列表數(shù)據(jù)不為桶號
bucket[data[i]] = 0 # 這時初始化從0將列表數(shù)據(jù)做桶號
bucket[data[i]] += 1 # 桶號依次加1
for j in range(bucket_len): # 遍歷桶
while bucket[j] > 0: # 將列表數(shù)據(jù)放在對應(yīng)桶號內(nèi)
data[count] = j
count += 1 # 計數(shù)個數(shù)加1
bucket[j] -= 1 # 個數(shù)減一,下一個相同的元素往前排
return data # 返回排序后的列表
data = [1, 2, 4, 1, 3, 5, 2, 2, 7, 3, 4]
print("排序前列表數(shù)據(jù):")
for i in range(11):
print("%2d" % data[i], end="")
print()
data2 = count_sort(data, 7) # 調(diào)用計數(shù)排序函數(shù)
print("排序后列表數(shù)據(jù):")
for j in range(11):
print("%2d" % data2[j], end="")以上就是python計數(shù)排序法的介紹,希望對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
網(wǎng)頁題目:創(chuàng)新互聯(lián)Python教程:python計數(shù)排序法是什么
網(wǎng)站鏈接:http://www.5511xx.com/article/djpcjjo.html


咨詢
建站咨詢
