1、冒泡排序、选择排序和插入排序的时间复杂度都是O(n^2),效率低。
# 冒泡排序
def bubble_sort(li):
for i in range(len(li)-1): # 第i趟
exchange = False
for j in range(len(li)-i-1):
if li[j] > li[j+1]:
li[j],li[j+1] = li[j+1],li[j]
exchange = True
print(li)
if not exchange:
return
# 选择排序
def select_sort(li):
for i in range(len(li)-1): # 第i趟
min_loc = i
for j in range(i+1, len(li)):
if li[j] < li[min_loc]:
min_loc = j
li[i], li[min_loc] = li[min_loc], li[i]
print(li)
# 插入排序
def insert_sort(li):
for i in range(1, len(li)): # i表示摸到的牌的下标
tmp = li[i]
j = i - 1 # j表示手里的牌的下标
while j>=0 and li[j]>tmp:
li[j+1] = li[j]
j -= 1
li[j+1] = tmp
print(li)
li=[3,1,2,6,8,5,4,7,9]
print(li)
print('bubble_sort')
li1 = li.copy()
bubble_sort(li1)
print('select_sort')
li2 = li.copy()
select_sort(li2)
print('insert_sort')
li3 = li.copy()
insert_sort(li3)
运行结果:
参考文献:B站教学视频——清华计算机博士带你学习Python算法和数据结构
2、冒泡排序与sorted排序比较,后者效率高很多。
import random
import time
import copy
# 冒泡排序
def bubble_sort(li):
for i in range(len(li)-1): # 第i趟
exchange = False
for j in range(len(li)-i-1):
if li[j] > li[j+1]:
li[j],li[j+1] = li[j+1],li[j]
exchange = True
if not exchange:
return
li1 = list(range(10000))
random.shuffle(li1)
li2 = li1.copy()
print(li1[:20])
print(li2[:20])
# bubble_sort
time_start = time.time()
bubble_sort(li1)
time_end = time.time()
print('bubble_sort costs %f s' % (time_end-time_start))
# sorted
time_start = time.time()
li2 = sorted(li2)
time_end = time.time()
print('sorted costs %f s' % (time_end-time_start))
print(li1[:20])
print(li2[:20])
运行结果: