Python 二分法(递归,while)

def binarysearch1(_list, target_num):
    low ,height, count= 0,len(_list)-1,0
    mid = hight // 2
    while count < mid:
        count += 1
        center = (low + hight) // 2
        if _list[center] > target_num:
            hight = center - 1
        elif _list[center] < target_num:
            low = center + 1
        else:
            return True
    return False


def binarysearch2(_list,target_num):
    mid = (len(_list))//2
    if len(_list) > 1:
        if _list[mid] > target_num:
            ret = binarysearch2(_list[:mid],target_num)
            return ret
        elif _list[mid] < target_num:
            ret = binarysearch2(_list[mid:],target_num)
            return ret
        else:
            return True
    else:
        if _list[0] == target_num:
            return True
        else:
            return False
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容