算法--练习题1

思路:利用二分法求解

def bin_search(data_set,val):
    low = 0
    high = len(data_set) - 1
    while low <= high:
        mid = (low + high) // 2 # 求中间值
        if data_set[mid] == val: # 输入值和中间值相等
            left = mid # 左边值为中间值
            right = mid # 右边值为中间值
            while left >= 0 and data_set[left] == val: # 左边值大于 0 ,左边值为选定的值
                left -= 1 # 向左边递进
            while right <= high and data_set[right] == val: # 右边值需要小于最右边的值 且 右边值 为 选定值
                right += 1 # 向右 递进
            return (left +1 , right - 1 )
        elif data_set[mid] < val: # 选定值 大于中间值
            low = mid + 1 # low 为 中间值 +1
        else: # 选定值 小于 中间值
            high = mid - 1 # high 为 中间值 - 1
    return

li = [1,2,3,3,3,4,4,5]
print(bin_search(li,4))

显示结果为:

 

posted @ 2018-06-24 16:33  追风的小蚂蚁  阅读(182)  评论(0编辑  收藏  举报