python实现二分查找

  • Post author:
  • Post category:python
def find(nums,num):
    start=0
    end=len(nums)
    while start<=end:
        mid=(start+end)/2
        if nums[mid]>num:
            end=mid-1
        elif nums[mid]<num:
            start=mid+1
        else:
            return mid
print find([1,2,3,4,5,6,7],3)

def find1(nums,num,start,end):
    if start<=end:
        mid=(start+end)/2
        if(nums[mid]>num):
            return find1(nums,num,start,mid-1)
        elif(nums[mid]<num):
            return find1(nums,num,mid+1,end)
        else:
            return mid
print find1([1,2,3,4,5,6,7],6,0,7)
            


版权声明:本文为zjcheer_up原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。