1 #冒泡排序,对列表进行升序排序 2 def bubble_sort(alist): 3 #相邻两个元素进行比较,如果发现位置错误就进行交换 4 n = len(alist) 5 for k in range(n-1): 6 for i in range(n-1-k): 7 if alist[i] > alist[i+1]: 8 alist[i],alist[i+1] = alist[i+1],alist[i] 9 alist = [4,7,32,6,9,10,34,24,7,8,67,40,78,88] 10 print('原数组:',alist) 11 bubble_sort(alist) 12 print('现数组:',alist)
1 原数组: [4, 7, 32, 6, 9, 10, 34, 24, 7, 8, 67, 40, 78, 88] 2 现数组: [4, 6, 7, 7, 8, 9, 10, 24, 32, 34, 40, 67, 78, 88]