冒泡排序的问题

Issue with bubble sorting

所以我决定在 Python 中创建一个气泡算法。问题是它对某些数字有效,但对其他数字无效。谁能帮忙:

def sort(number):
    to_sort = list(str(number))
    sorted_list = sorted(to_sort)
    print(sorted_list)
    i = 0
    while True:
        if to_sort == sorted_list:
            print(f"Sorted {number} to {''.join(to_sort)}" )
            break
        first_index = to_sort[i]
        try:
            second_index = to_sort[i+1]
        except IndexError:
            i = 0
        if first_index < second_index:
            i += 1
            print(to_sort)
            continue
        elif first_index > second_index:
            print(f"switching {to_sort[i+1]} to {first_index}")
            to_sort[i+1] = first_index
            print(to_sort)
            print(f"Switching {to_sort[i]} to {second_index}")
            to_sort[i] = second_index
            print(to_sort)
            i += 1
            continue

sort(49304)

它适用于 51428 但不适用于 49304。有人知道为什么吗?

致命缺陷在于您的循环重置(至 0),以及您断开连接的交换逻辑。

    first_index = to_sort[i]
    try:
        second_index = to_sort[i+1]
    except IndexError:
        i = 0
    ...
    elif first_index > second_index:
        ...
        to_sort[i] = second_index

在 运行 不在列表末尾的情况下,second_index 现在有错误的值:它是 previous 值,因为你从来没有在循环 i 回到 0 后重置它。

(1) 通过插入重置来解决您眼前的问题:

    except IndexError:
        i = 0
        second_index = to_sort[0]

(2) 研究现有的冒泡排序。除此之外,让您的交流更简单。

    to_sort[i], to_sort[i+1] = to_sort[i+1], to_sort[i]

控制i使其不越界。请注意,您不必真正担心将最后一个元素与第一个元素交换:冒泡排序不会像那样跳过结尾。