使用循环和递归方法实现二分法搜索

来源:互联网 发布:网络协议基础知识 编辑:程序博客网 时间:2024/05/18 20:52

对于已排序的序列,实现二分法搜索算法,有循环和递归两种策略。

对于这种算法,中心点一直是一个开区间,因此下一次搜索时新区间应该相应的+-1,从而最终start>end

# -*- coding: utf-8 -*-def binarysearch1(l, item):    start = 0    end = len(l) - 1    while start <= end:        mid = (start + end)/2        if l[mid] < item:            start = mid + 1        elif l[mid] > item:            end = mid -1        else:            return mid    return -1def binarysearch_recur1(l, item):    start = 0    end = len(l) - 1    def binarysearch_recur_pack(l, item, start, end):        if start <= end:            mid = (start + end)/2            if l[mid] < item:                start = mid + 1            elif l[mid] > item:                end = mid - 1            else:                return mid            result = binarysearch_recur_pack(l, item, start, end)            if result == -1:                return -1            else:                return result        else:            return -1    return binarysearch_recur_pack(l, item, start, end)l = [1, 6, 8, 9, 14, 36, 77, 90]print binarysearch1(l, 5)print binarysearch_recur1(l, 78)


1 0
原创粉丝点击