sách gpt4 ăn đã đi

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

In lại Tác giả: Walker 123 更新时间:2023-12-01 00:45:23 25 4
mua khóa gpt4 giày 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))

câu trả lời hay nhất

您忘记使用以下结果:

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
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress