为什么我的递归气泡排序不起作用?

时间:2019-07-14 01:59:55

标签: python recursion bubble-sort

当我在列表上运行递归气泡时:

 ["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))

1 个答案:

答案 0 :(得分:2)

您忘记使用以下结果:

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']