# 快速排序defquicksort(list,left,right):
l = left # 数组左边界
r = right # 数组右边界
temp =list[left]# 枢轴while left<right:if(list[right]<temp and left<right):list[left]=list[right]
left +=1while left<right:if(list[left]>temp):list[right]=list[left]
right -=1breakelse:
left +=1else:
right-=1list[left]= temp
if(l<left):return quicksort(list,l,left-1)if(r>right):return quicksort(list,left+1,r)returnlistif __name__ =='__main__':
a =[5,4,3,8,7,11,2,6,-3,-1,-4,9,22]# a.sort()
b =sorted(a)# 目的是让sorted结果和我的快速排序结果做对比print('sort',b)
b = quicksort(a,0,len(a)-1)print(b)
输出:
剪枝策略的冒泡排序
defbub_sort(list):
mark =len(list)-1
cou =0while(mark!=0):for i inrange(mark):if(list[i]>list[i+1]):
temp =list[i+1]list[i+1]=list[i]list[i]= temp
cou +=1if(cou ==0):breakelse:
cou =0
mark-=1returnlistif __name__ =='__main__':list=[1,3,5,7,9,2,4]
num =9# m = half_search(list,left=0,right=len(list)-1,num=num)
m = bub_sort(list)print(m)
快速排序代码# 快速排序def quicksort(list,left,right): l = left # 数组左边界 r = right # 数组右边界 temp = list[left] # 枢轴 while left<right: if(list[right]<temp and left<right): ...