defbububle_sort(alist): """冒泡排序(稳定|n^2m)""" n = len(alist) for j in range(n-1): count = 0 for i in range(0,n-1-j): if alist[i]>alist[i+1]: count +=1 alist[i], alist[i+1] = alist[i+1], alist[i] if count==0: return
二、选择排序
defselect_sort(alist): """选择排序(不稳定|n^2)""" n = len(alist) for j in range(n-1): min_index = j for i in range(j+1,n): if alist[min_index] > alist[i]: min_index = i alist[j], alist[min_index] = alist[min_index], alist[j]
三、插入排序
definsert_sort(alist): """插入排序(稳定|n^2)""" n = len(alist) for j in range(1,n): i = j while i>0: if alist[i] < alist[i-1]: alist[i], alist[i-1] = alist[i-1], alist[i] i -= 1 else: break
四、希尔排序
defshell_sort(alist): """希尔排序(不稳定|n^2)""" n = len(alist) gap = n//2
while gap>=1: for j in range(gap,n): i=j while i>0: if alist[i]<alist[i-gap]: alist[i], alist[i-gap] = alist[i-gap], alist[i] i -= gap else: break gap //=2
五、快速排序
defquick_sort(alist, first, last): """快速排序(不稳定|n^2)""" if first >= last: return mid_value = alist[first] low = first high = last while low < high: #high左移 while low <high and alist[high] >= mid_value: high -= 1 alist[low] = alist[high] #low右移 while low < high and alist[low] < mid_value: low += 1 alist[high] =alist[low] #从循环退出时,low=high alist[low] = mid_value