gpt4 book ai didi

python - 使用基数排序对负数和正数进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:19:46 26 4
gpt4 key购买 nike

<分区>

我正在尝试利用基数排序对无序整数列表进行排序,包括正整数和负整数。我有能力对正数列表进行排序,但我对如何对负数使用基数排序感到困惑。我想知道是否有人可以帮助我编码和解释基数排序如何处理负数的部分。经过一番谷歌搜索后,我了解到您必须将负号视为特殊字符,但我仍在困惑的火车上。下面你可以看到我目前的基数排序实现,取自 https://gist.github.com/rizkyabdilah/1740053 .

def radix_sort(random_list):
len_random_list = len(random_list)
modulus = 10
div = 1
while True:
# empty array, [[] for i in range(10)]
new_list = [[], [], [], [], [], [], [], [], [], []]
for value in random_list:
least_digit = value % modulus
least_digit /= div
new_list[least_digit].append(value)
modulus = modulus * 10
div = div * 10

if len(new_list[0]) == len_random_list:
return new_list[0]

random_list = []
rd_list_append = random_list.append
for x in new_list:
for y in x:
rd_list_append(y)

random_data = [13, 8, 1992, 31, 3, 1993, 1, 0, -1]
print radix_sort(random_data)

感谢您的帮助!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com