[英]Trouble implementing a counting sort algorithm
我正在嘗試教自己一些使用python進行排序的算法,但輸出出現了一些麻煩。 我正在嘗試實現一種計數排序算法,到目前為止,我已經做到了:
def counting_sort(l):
nums = l
highest = max(nums) + 1
helper_list = [0] * highest
s_list = []
for i in range(len(nums)):
value = nums[i]
helper_list[value] += 1
for j in range(len(helper_list)):
s_list.append([j] * helper_list[j])
return s_list
一切都差不多了 ,但是當我輸入[5, 2, 2, 3, 1, 2]
。
我得到的輸出如下: [[], [1], [2, 2, 2], [3], [5]]
。
您只需將“附加”更改為“擴展”。 append函數將一個元素添加到您的列表,在本例中為另一個列表。 擴展功能將您的列表與作為參數給出的列表連接在一起。
您的功能應如下所示:
def counting_sort(elements):
highest = max(elements) + 1
helper_list = [0] * highest
s_list = []
for value in elements:
helper_list[value] += 1
for j in range(len(helper_list)):
s_list.extend([j] * helper_list[j])
return s_list
問題是這一行:
s_list.append([j] * helper_list[j])
這表示將列表( [j]*helper_list[j]
)附加到s_list
,並將該列表添加為新元素或s_list
。
相反,您想要將一個列表添加到另一個列表中,可以這樣進行:
s_list.append += ([j] * helper_list[j])
def counting_sort(unordered_list, k, desc=False):
'''
unordered_list is the input array to be sorted.
k is the range of non-negative key values.
desc lets the algorithm to sort the array in descending order.
time complexity is the sum of the times for two steps, O(n + k).
'''
count_list = [0] * k
for element in unordered_list:
count_list[element] += 1
if desc:
enumerator = reversed(list(enumerate(count_list)))
else:
enumerator = enumerate(count_list)
sorted_list = []
for idx, count in enumerator:
sorted_list += [idx] * count
return sorted_list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.