插入排序
加入了绘制动态图的代码,可以直观地看到排序过程
import matplotlib.pyplot as plt
import time
def insert_sort(lst):
lsts = []
for i in range(len(lst)):
temp = lst[i]
j = i-1
while j>=0 and lst[j]>temp:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = temp
l = lst[:]
lsts.append(l)
return lsts
if __name__ == "__main__":
lst = [13,32,42,1,53,4,66,2,5,7,74,23]
lsts = insert_sort(lst)
plt.ion()
fig = plt.figure()
ax = plt.gca()
bars = ax.bar(range(len(lst)),height=lst)
for l in lsts:
print(l)
bars.remove()
bars = ax.bar(range(len(lst)),height=l)
plt.pause(0.5)
while True:#防止图片关闭
plt.pause(1)
选择排序
def select_sort(lst):
for i in range(len(lst)):
min_index = i
for j in range(i,len(lst)):
if lst[j]<lst[min_index]:
min_index = j
lst[i],lst[min_index] = lst[min_index],lst[i]
print(lst)
快速排序
def partition(lst,low,high):
'''
low是起始index
high是终止index
lst是数组
'''
temp = lst[high-1]
small = low-1
for i in range(low,high):
if lst[i]<temp:
small += 1#small用于记录最后一个小于temp的元素的index
if small != i:
lst[small],lst[i] = lst[i],lst[small]#交换的出发条件是发现了比temp小的元素
if lst[small+1] > temp:
lst[small+1],lst[high-1] = lst[high-1],lst[small+1]
return small+1
def quick_sort(lst,low,high):
if low < high:
p = partition(lst,low,high)
quick_sort(lst,low,p)
quick_sort(lst,p+1,high)
return None
有兴趣转行机器学习的朋友可以加群:
机器学习-菜鸡互啄群
网友评论