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

标签 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))

最佳答案

您忘记使用以下结果:

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/

相关文章:

python - 交互模式与非交互模式下相同代码中的不同导入行为 - 为什么模块搜索路径不同?

python 2.7 到 python 3.2 字符串格式错误

java - 打印二叉搜索树中序遍历

c# - 从数据库获取结果时防止循环引用

java - 解决 "Partition Function Q"或总和为 n 的序列总数的有效方法

Java冒泡排序算法

java - 使用二维数组进行冒泡排序

python - Matplotlib 直方图(基础题)

python - 如何将元组列表作为 OpenAI Gym 中的操作空间传递?

algorithm - 对于已排序的数据,哪种排序方法最快?