问题描述
因此,我决定在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
,使其不会超出范围。请注意,您不必真正担心将最后一个元素与第一个元素交换:冒泡排序不会跳过这样的结尾。