题目
代码
原始排序
def bubbleSort(alist):
for i in range(len(alist)):
for j in range(len(alist) - i -1):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1] , alist[j]
return alist
第一次改进
def bubbleSort2(alist):
flag = False # 设置标记
for i in range(len(alist)):
for j in range(len(alist) - i -1):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1] , alist[j]
flag = True # 只要还能排序就置True
if not flag: # 排序好后就停止
return alist
return alist
第二次改进
def bubbleSort3(alist):
count = len(alist)
for i in range(count):
for j in range(i+1, count): # 每次循环只从未排序的序列中取出第一个数
if alist[i] > alist[j]:
alist[i], alist[j] = alist[j], alist[i]
return alist
调用
alist = list(map(int,input("Enter a list:").split( )))
after_sort_list = bubbleSort(alist)
after_sort_list2 = bubbleSort2(alist)
after_sort_list3 = bubbleSort3(alist)
print(after_sort_list)
print(after_sort_list2)
print(after_sort_list3)
输入
Enter a list:1 4 2 3
输出
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]