vlambda博客
学习文章列表

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))