1、冒泡排序
1 def bubbleSort(list): 2 for i in range(len(list)): 3 for j in range(len(list)-1,i,-1): 4 if list[j-1]>list[j]: 5 temp=list[j-1] 6 list[j-1]=list[j] 7 list[j]=temp 8 9 return list
2、归并排序
1 def Merge(list,templist,left,middle,right): 2 leftEnd=middle-1 3 rightStart=middle 4 tempIndex=left 5 tempLen=right-left+1 6 7 while left<=leftEnd and rightStart<=right: 8 if list[left]<list[rightStart]: 9 templist[tempIndex]=list[left] 10 tempIndex+=1 11 left+=1 12 else: 13 templist[tempIndex]=list[rightStart] 14 tempIndex+=1 15 rightStart+=1 16 17 while left<=leftEnd: 18 templist[tempIndex]=list[left] 19 tempIndex+=1 20 left+=1 21 22 while rightStart<=right: 23 templist[tempIndex]=list[rightStart] 24 tempIndex+=1 25 rightStart+=1 26 27 for i in range(tempLen): 28 list[right]=templist[right] 29 right-=1 30 31 def MergeSort(list,templist,left,right): 32 if left<right: 33 middle=(left+right)//2 34 MergeSort(list,templist,left,middle) 35 MergeSort(list,templist,middle+1,right) 36 Merge(list,templist,left,middle+1,right) 37 return list
3、快速排序
1 def Division(list,left,right): 2 base=list[left] 3 while left<right: 4 while left<right and list[right]>=base: 5 right-=1 6 list[left]=list[right] 7 8 while left<right and list[left]<=base: 9 left+=1 10 list[right]=list[left] 11 12 list[left]=base 13 return left 14 15 16 def QuickSort(list,left,right): 17 if left<right: 18 i=Division(list,left,right) 19 QuickSort(list,left,i-1) 20 QuickSort(list,i+1,right)
4、堆排序
1 def HeapAdjust(list,parent,length): 2 temp=list[parent] 3 child=2*parent+1 4 while child<length: 5 if child+1<length and list[child]<list[child+1]: 6 child=child+1 7 if temp>=list[child]: 8 break 9 list[parent]=list[child] 10 parent=child 11 child=2*parent+1 12 list[parent]=temp 13 14 def HeapSort(list): 15 for i in range(len(list)//2-1,-1,-1): 16 HeapAdjust(list,i,len(list)) 17 for i in range(len(list)-1,0,-1): 18 temp=list[0] 19 list[0]=list[i] 20 list[i]=temp 21 HeapAdjust(list,0,i) 22 return list