‘‘‘冒泡排序:比较相邻的元素,如果第一个比第二个大,就交换位置‘‘‘ import time start = time.time() def bubble_sort (alist): # 从8-0遍历,step = -1,倒着来. for j in range (len(alist)-1,0,-1): # j = 8,7,6,5,4,3,2,1 # 第一次把最后一个排好了,所以第二次不用比较最后一个 for i in range(j): if alist[i] > alist[i+1]: alist[i], alist[i+1] = alist[i+1], alist[i] if __name__ ==‘__main__‘: li = [54,26,93,17,77,31,44,55,20] bubble_sort(li) print(li) end = time.time() print(end-start)
时间: 2024-11-06 12:40:11