插入排序和冒泡排序的概念我就不解释了吧
。。。插入排序代码:
1 if __name__ ==‘__main__‘: 2 l = [4,1,9,13,34,26,10,7,4] 3 4 #=========================insert_sort========================= 5 def insert_sort(l): 6 for i in range(len(l)): 7 min_index = i 8 for j in range(i+1,len(l)): 9 if l[min_index] > l[j]: 10 min_index = j 11 tmp = l[i] 12 l[i] = l[min_index] 13 l[min_index] = tmp 14 print(str(l)) 15 print("result: " + str(l)) 16 17 insert_sort(l) 18 print("insert_sort success!!!")
每次遍历,先假设list[min_index]处的值最小,再跟后面的值依次比较,当发现list[j]比list[min_index]值小时,这时的min_index替换为j,再跟后面的进行比较,指导找到最小的那个list[j],将j付给min_index,这时l[min_index]就是遍历过程中的最小值了,不知道说清楚了没~~
结果如下:
[1, 4, 9, 13, 34, 26, 10, 7, 4] [1, 4, 9, 13, 34, 26, 10, 7, 4] [1, 4, 4, 13, 34, 26, 10, 7, 9] [1, 4, 4, 7, 34, 26, 10, 13, 9] [1, 4, 4, 7, 9, 26, 10, 13, 34] [1, 4, 4, 7, 9, 10, 26, 13, 34] [1, 4, 4, 7, 9, 10, 13, 26, 34] [1, 4, 4, 7, 9, 10, 13, 26, 34] [1, 4, 4, 7, 9, 10, 13, 26, 34] result: [1, 4, 4, 7, 9, 10, 13, 26, 34] insert_sort success!!!
下面再来看冒泡排序
1 #==========================bubble_sort======================== 2 3 def bubble_sort(l): 4 for i in range(len(l),0,-1): 5 for j in range(len(l)-1): 6 if l[j] > l[j+1]: 7 tmp = l[j] 8 l[j] = l[j+1] 9 l[j+1] = tmp 10 11 print("result: " + str(l)) 12 13 bubble_sort(l) 14 print("bubble_sort success!!!")
不解释了。。
时间: 2024-10-14 00:50:20