gpt4 book ai didi

python - 为什么我的递归冒泡排序不起作用?

转载 作者:行者123 更新时间:2023-12-01 00:45:23 25 4
gpt4 key购买 nike

当我在列表上运行递归冒泡排序时:

 ["4213", "4201", "4204", "4218", "4205", "Out"]

我得到:

['4201', '4204', '4213', '4205', '4218', 'Out']

而不是正确答案。谁能解释一下为什么吗?

def test_sort(list_to_sort):
length = len(list_to_sort)
if length == 0:
return list_to_sort
for i in range(0, length - 1):
if list_to_sort[i] > list_to_sort[i + 1]:
(list_to_sort[i], list_to_sort[i + 1]) = (list_to_sort[i + 1], list_to_sort[i])
test_sort(list_to_sort[:length - 1])
return list_to_sort

def main():
testlist = ["4213", "4201", "4204", "4218", "4205", "Out"]
print(test_sort(testlist))

最佳答案

您忘记使用以下结果:

test_sort(list_to_sort[:length - 1])

您可以将其更改为:

list_to_sort[:length - 1] = test_sort(list_to_sort[:length - 1])

测试代码:

def test_sort(list_to_sort):
length = len(list_to_sort)
if length < 2:
return list_to_sort
for i in range(0, length - 1):
if list_to_sort[i] > list_to_sort[i + 1]:
list_to_sort[i:i + 2] = list_to_sort[i + 1], list_to_sort[i]
list_to_sort[:length - 1] = test_sort(list_to_sort[:length - 1])
return list_to_sort


def main():
testlist = ["4213", "4201", "4204", "4218", "4205", "Out"]
print(test_sort(testlist))

main()

结果:

['4201', '4204', '4205', '4213', '4218', 'Out']

关于python - 为什么我的递归冒泡排序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024032/

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