选择排序:
def sel_sort(arr): i=0; length =len(arr) while i<length: j = i+1 min = arr[i] while j<length: if arr[j]<min: min = arr[j] arr[j] = arr[i] arr[i] = min j+=1 i+=1 return arr
插入排序:
def insert_sort(arr): i =1 while i <=len(arr)-1: key = arr[i]; j =i -1 i +=1 while j >=0 and arr[j]>key: arr[j+1] = arr[j] j -=1 arr[j+1] = key return arr a = insert_sort([1,2,4,3]) print(a)
归并排序:
#子问题程序(对两组已排序数组进行合并排序)最小子程序数组长度为2,即p=q时 #0<=p<=q<r<=len(a), def merge(arr,p,q,r): left = arr[p:q+1] right = arr[q+1:r+1] left.append(100000)#哨兵 right.append(100000) i=0;j=0; k=r+1; while p<k: if left[i]<=right[j]:#比较,交换位置 arr[p] = left[i] i +=1 else : arr[p] = right[j] j+=1 p+=1 return arr def merge_sort(arr,p,r):#主程序,迭代,参数同merge if p<r: q = int((p+r)/2) merge_sort(arr,p,q) merge_sort(arr,q+1,r) merge(arr,p,q,r) return arr #demo arr = [2,4,1,7,6] a= merge_sort(arr,0,4) print(a)
快速排序:
#子程序,划分数组(【小于中间值,中间值,大于中间值】),return中间值r+1 def part(arr,p,r): x = arr[r] i = p-1 j= p while j<r: if arr[j]<x: i+=1 arr[i],arr[j]=arr[j],arr[i] j+=1 arr[i+1],arr[r] = arr[r],arr[i+1] return i+1 def quick_sort(arr,p,r):#主程序 if p<r: q = part(arr,p,r) quick_sort(arr,p,q-1) quick_sort(arr,q+1,r) part(arr,p,r) return arr
未完待续...
来源:https://www.cnblogs.com/dingblog/p/4040587.html