#coding=utf-8#快速排序defquick_sort(alist,first,last):'''快速排序'''if first>=last:return
mid_value=alist[first]
low=first
high=last
while low<high:#一次的快速排序while low<high and alist[high]>=mid_value:#如果有相等的值 尽量放到一边
high -=1
alist[low]= alist[high]while low<high and alist[low]<mid_value:
low +=1
alist[high]=alist[low]
alist[low]=mid_value
# 第一次结束后 alist[:low-1] alist[low+1:]#对low左边的列表执行快速排序
quick_sort(alist,first,low-1)#对low右边的列表执行快速排序
quick_sort(alist,low+1,last)if __name__ =='__main__':
li =[54,336,93,17,77,31,44,55,20]print(li)
quick_sort(li,0,len(li)-1)print(li)
运行结果:[54,336,93,17,77,31,44,55,20][17,20,31,44,54,55,77,93,336]
6.归并排序
时间复杂度 最优时间复杂度:O(nlogn) 最坏时间复杂度:O(nlogn) 稳定性:稳定
#coding=utf-8#归并排序defmerge_sort(alist):'''归并排序'''
n =len(alist)if n<=1:return alist
mid = n//2#将列表分成两部分#left 采用归并排序后形成的有序的新的列表
left_li = merge_sort(alist[:mid])#right 采用归并排序后形成的有序的新的列表
right_li = merge_sort(alist[mid:])#以上代码为拆分过程# 以下代码是将两个有序的子序列合并为一个新的整体#merge(left,right)
left_pointer, right_pointer =0,0
result =[]while left_pointer <len(left_li)and right_pointer <len(right_li):if left_li[left_pointer]<=right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer +=1else:
result.append(right_li[right_pointer])
right_pointer +=1
result += left_li[left_pointer:]
result += right_li[right_pointer:]return result
if __name__ =="__main__":
li =[54,93,17,77,31,44,55,20]print(li)
sorted_li = merge_sort(li)print(li)print(sorted_li)
运行结果:[54,93,17,77,31,44,55,20][54,93,17,77,31,44,55,20][17,20,31,44,54,55,77,93]#原数列不变,在新创建的数列进行操作
7. 常见排序算法效率比较
8. 二分查找(折半查找)
时间复杂度 最优时间复杂度:O(1) 最坏时间复杂度:O(logn)
递归方法
#coding=utf-8#二分查找(递归)defbinary_search(alist,item):'''二分查找(递归)'''
n =len(alist)if n >0:
mid=n//2if alist[mid]==item:returnTrueelif item<alist[mid]:return binary_search(alist[:mid],item)else:return binary_search(alist[mid+1:],item)returnFalseif __name__=='__main__':
li =[17,20,31,44,54,55,77,93]print(binary_search(li,55))print(binary_search(li,100))print(binary_search(li,54))
运行结果:TrueFalseTrue
非递归方法
#coding=utf-8#二分查找(非递归)defbinary_search01(alist,item):'''二分查找(非递归)'''
n=len(alist)
first =0
last = n-1while first<=last:
mid=(first+last)//2if alist[mid]==item:returnTrueelif alist[mid]>item:
last=mid-1else:
first=mid+1returnFalseif __name__=='__main__':
li =[17,20,31,44,54,55,77,93]print(binary_search01(li,55))print(binary_search01(li,100))print(binary_search01(li,54))
运行结果:TrueFalseTrue