python快速排序,合并排序,二分查找
Posted 中学生大课堂
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python快速排序,合并排序,二分查找相关的知识,希望对你有一定的参考价值。
def quick_sort(alist,start,end):
left=start
right=end
mid=alist[start]
while left < right:
while left<right and alist[right]>=mid:
right -=1
alist[left]=alist[right]
while left<right and alist[left]<mid:
left +=1
alist[right]=alist[left]
alist[left]=mid
quick_sort(alist,start,left-1)
quick_sort(alist,left+1,end)
def merge_sort(alist):
if len(alist)==1:
return alist
mid=len(alist)//2
left=alist[:mid]
right=alist[mid:]
ll=merge_sort(left)
rl=merge_sort(right)
return merge(ll,rl)
def merge(left,right):
result=[]
while len(left)>0 and len(right)>0:
if left[0]<=right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result+=left
result+=right
return result
def bin_search(alist,item):
n=len(alist)
if n==0:
return False
mid=n//2
if alist[mid]==item:
return True
elif alist[mid]<item:
return bin_search(alist[:mid],item)
else:
return bin_search(alist[mid+1:],item)
if __name__ == '__main__':
alist=[1,12,43,5,2,55]
print(alist)
#quick_sort(alist,0,len(alist)-1)
print(alist)
print("merge")
alist = [1, 12, 43, 5, 2, 55]
print(alist)
list2=merge_sort(alist)
print(list2)
print("bin")
alist = [1, 12, 43, 5, 2, 55]
print(bin_search(alist,55))
以上是关于python快速排序,合并排序,二分查找的主要内容,如果未能解决你的问题,请参考以下文章
Java八股文面试题 基础篇 -- 二分查找算法冒泡排序选择排序插入排序希尔排序快速排序