【问题标题】:Issue with bubble sorting冒泡排序问题
【发布时间】:2020-12-19 23:59:46
【问题描述】:

所以我决定在 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。有人知道为什么吗?

【问题讨论】:

  • 我认为,当您捕获异常时,您应该重新启动循环。你需要 i = 0;继续。否则你的“索引”变量不会被重置。
  • 您说“它适用于 51428 但不适用于 49304”。你在 49304 上试一试,结果如何?

标签: python algorithm bubble-sort


【解决方案1】:

致命缺陷在于您的循环重置(为 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,使其不会越界。请注意,您不必真正担心将最后一个元素与第一个元素交换:冒泡排序不会像那样跳过结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2021-08-15
    • 2021-01-29
    • 2019-04-18
    相关资源
    最近更新 更多