"找到给定list中最小元素的index"deffind_min_index(lst):#假设最小是lst[0],对比后有更小的将之替换
smallest = lst[0]
min_index =0for i inrange(1,len(lst)):if lst[i]< smallest:
smallest = lst[i]
min_index = i
return min_index
defselection_sort(lst):for i inrange(len(lst)):# j 是对于原list最小数的index
j = find_min_index(lst[i:])+ i
# swap the elements at i and j
lst[i], lst[j]= lst[j], lst[i]return lst
defmerge(lst1, lst2):
res =[]
n1, n2 =len(lst1),len(lst2)
i, j =0,0while i < n1 and j < n2:if lst1[i]<= lst2[j]:
res +=[lst1[i]]
i +=1else:
res +=[lst2[j]]
j +=1return res + lst1[i:]+ lst2[j:]defmergesort(ls):iflen(ls)<=1:return ls
else:
sub1 = mergesort(ls[:len(ls)//2])
sub2 = mergesort(ls[len(ls)//2:])return merge(sub1, sub2)
# use iteration to quick sortdefquick_sort(lst):# if only 1 element in lst, return directlyiflen(lst)<2:return lst
# choose mid-term as pivot
mid = lst[len(lst)//2]# define left&right part of pivot
left, right =[],[]# remove mid-term
lst.remove(mid)for item in lst:if item >= mid:
right.append(item)else:
left.append(item)# important: use iterationreturn quick_sort(left)+[mid]+ quick_sort(right)
1. 插入排序 图1 插入排序(图片引用来自:https://cuijiahua.com/blog/2017/12/algorithm_2.html)def insert_sorting(lst): for i in range(1,len(lst)): while lst[i] < lst[i-1] and i > 0: lst[i], lst[i-1] = lst[i-1], lst[i] i -