算法一 二分查找( by Python)

1.查找问题分析

假设你要在字典中查找一个单词,而该字典包含24000个单词,你认为每种查找最多需要多少步?
如果要查找的单词位于字典末尾,使用简单查找将需要24000步。使用二分查找时,每次排除一半单词,直到最后只剩下一个单词。
这里写图片描述

2. Python实现二分查找

def binary_search(list, item):
    low = 0
    height = len(list)-1

    while low <= height:
        mid = (low+height) / 2
        temp = list[mid]

        if temp == item:
            return  mid
        if temp > item:
            height = mid-1       
        else:
            low = mid+1

    return None

mdata = [1, 4, 7, 9, 14, 16]
index = binary_search(mdata, 14)
print("index=", index)
发布了40 篇原创文章 · 获赞 37 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/sanyang730/article/details/79234013
今日推荐