冒泡排序
1 def bubble_sort(li): 2 '''本算法复杂度为O(n**2)''' 3 for i in range(len(li)-1):# 列表长度为n,需要n-1趟 4 ''' 5 i的取值个数为n-1 6 i=0时,j的取值个数为n-1 7 i=1时,j的取值个数为n-1-1 8 i=2时,j的取值个数为n-1-1-1 9 故对于i,j的取值个数为n-1- 10 ''' 11 for j in range(len(li)-1-i): 12 # 若后面的数小于前面数,则两数前后交换 13 if li[j] > li[j+1]: 14 li[j],li[j+1] = li[j+1],li[j] 15 li = [random.randint(0,10000) for i in range(10000)] 16 print(li) 17 bubble_sort(li) 18 print(li)
选择排序
# 选择排序 # 一趟排序记录最小的数,放到第一个位置 # 再一趟排序记录记录无序区最小的数,放到第二个位置 # ...... # 算法关键的:有序区和无序区,无序去最小数的位置 # 本算法复杂度为O(n**2) def select_sort(li): for i in range(len(li)-1): # 需要排n-1趟 tmp = i # tmp用来记录无序区最小的数的索引 for j in range(i+1,len(li)): ''' j的范围即无序区范围 i=0时,j的范围是1到最后 i=1时,j的范围是2到最后 ...... ''' if li[j]<li[tmp]: tmp=j li[i],li[tmp] = li[tmp],li[i] # li = [23,35,3,23,23,2,1,4,34,23,4,3,23,5,23,2,34,23,23,2,34,2,4534,6,7,4,6,8,3,42] # li = [random.randint(0,10000) for i in range(1000)] # print(len(li),li) # select_sort(li) # 用时0.053 # print(li) # li = [random.randint(0,10000) for i in range(10000)] # print(len(li),li) # select_sort(li) # 用时6.057 # print(li)
插入排序
本算法时间复杂度也是O(n**2)
1 def insert_sort(li): 2 for i in range(1,len(li)): 3 tmp = li[i] 4 j = i-1# j指手里的牌的下标 5 while j>=0 and li[j] > tmp: 6 li[j+1] = li[j] 7 j -= 1 8 li[j+1] = tmp 9 # li = [3,2,5,6,4,3,6,7,5,7,6,45,7,8,8,34] 10 # print(insert_sort(li)) 11 li = [random.randint(0,10000) for i in range(1000)] 12 print(li) 13 insert_sort(li)# 0.049 14 print(li)# 15 16 li = [random.randint(0,10000) for i in range(10000)] 17 print(li) 18 insert_sort(li)# 5.46 19 print(li)#