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

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


咨詢
建站咨詢
