这个冒泡排序算法每次运行时都会打印一个空列表,真的不会看到它的问题:
def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
print(seq)
return None
if __name__ == '__main__':
bubble_sort(list(range(0,10,-1)))
答案 0 :(得分:1)
list(range(0, 10, -1))
给出一个空列表[],因为范围从0到10,步长为......
尝试list(range(10, 0, -1))
def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i + 1]:
seq[i], seq[i + 1] = seq[i + 1], seq[i]
changed = True
print(seq)
return None
if __name__ == '__main__':
# l = list(range(0, 10, -1)) # Wrong :-)
l = list(range(10, 0, -1))
print l
bubble_sort(l)
结果
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
更新:如果你想递归地做,但没有作弊: - )......
def bubble_sort(input_list):
for idx, num in enumerate(input_list):
try:
if input_list[idx + 1] < num:
input_list[idx] = input_list[idx + 1]
input_list[idx + 1] = num
bubble_sort(input_list)
except IndexError:
pass
return input_list
if __name__ == '__main__':
my_list = [100, 39, 2, 12, 42, 12, 90]
bubble_sort(my_list)
print(my_list)