python算法-search顺序查找

# @ Time : 2020/11/13 12:04
# @ Author : Ellen

def search(li, item):
    """无序列表"""
    # pos = 0
    # while pos < len(li):
    #     if li[pos] == item:
    #         return True
    #     else:
    #         pos += 1
    # return False

    """有序列表"""
    pos = 0
    while pos < len(li):
        if li[pos] == item:
            return True
        else:
            if li[pos] > item:
                return False
            else:
                pos += 1
    return False


if __name__ == '__main__':
    tlist = [1, 2, 8, 13, 17, 19,  32,42]        # 有序
    # tlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]   无序
    print(search(tlist, 2))
    print(search(tlist, 15))

执行结果:
True
False

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/109672969