二分查找

递归二分查找

def binsearch(array,low,high,k):
    if low <= high:
        mid=(low+high)//2
        if array[mid]==k:
            return mid
        elif k>array[mid]:
            return binsearch(array,mid+1,high,k)
        else:
            return binsearch(array,low,mid-1,k)
    else:
        return -1

 非递归二分查找

def binSearch(array,k):
    low=0
    high=len(array)-1

    while low<=high:
        mid=(low+high)//2
        if array[mid]==k:
            return mid
        elif array[mid]>k:
            high=mid-1
        else:
            low=mid+1

    return -1

 带重复元素的有序数组返回查找元素第一次出现的位置

def bSearch(arr,k):
    if len(arr)==0:
        return -1
    low=0
    high=len(arr)-1
    while low<=high:
        mid=(low+high)//2
        if arr[mid]>k:
            while mid>low and arr[mid]==arr[mid-1]:
                mid-=1
            high=mid-1
        elif arr[mid]<k:
            while mid<high and arr[mid]==arr[mid+1]:
                mid+=1
            low=mid+1
        else:
            while mid>low and arr[mid]==arr[mid-1]:
                mid-=1
            return mid
  return -1

 

posted @ 2017-12-19 14:12  光彩照人  阅读(232)  评论(0编辑  收藏  举报