zoukankan      html  css  js  c++  java
  • 数据结构和算法-查找算法-列表查找以及二分查找

    #########################################################

    """
    一、列表查找
    1、列表查找:从列表中查找指定元素
    输入:列表、待查找元素
    输出:元素下标或未查找到元素
    
    2、顺序查找:从列表第一个元素开始,顺序进行搜索,直到找到为止。
    返回找到的那个索引
    
    3、二分查找:从有序列表的候选区data[0:n]开始,通过对待查找的值与候选区中间值的比较,可以使候选区减少一半。
    二分查找:时间复杂度是O(logn)
    二分查找的前提:列表是有序的
    切片的复杂读是O(n) #因为切的时候是赋值的
    
    
    """

    ##################     二分查找      #######################

    # 二分查找,
    # 优点是比较次数少,查找速度快,平均性能好
    # 其缺点是要求待查表为有序表,且插入删除困难
    # 适用于不经常变动而查找频繁的有序列表
    
    # 如果判断是中间位置,计算公式是下标之和除以2,
    # 代码逻辑,最好的办法是使用递归实现,
    
    # 第一种方式,使用递归来实现
    def binary_search(alist, item):
        n= len(alist)
        mid = n //2
        if n>0:
            if alist[mid] == item:  # 如果找的数字和中间值一样,就直接返回true了,
                return True
            elif item <alist[mid]:  # 如果查找到的数字比中间值小,就对左边的子表进行递归,
                return binary_search(alist[:mid],item)
            else:  # 如果查找到的数字比中间值大 ,就对右边的子表进行递归,
                return binary_search(alist[mid+1:], item)
        return False  # 如果递归结束了,还没有找到就是没有这个内容,
    
    # 第二种方式非递归方式,
    def binary_search2(alist, item):
        n=len(alist)
        first = 0
        last = n-1
        while first <= last :  # 如果找的时候,开始的坐标小于结束了,就结束了,等于的时候就是一个元素的时候,
            mid = (first + last) // 2
            if alist[mid] == item:
                return True
            elif item<alist[mid]:
                last = mid - 1
            else:
                first = mid + 1
        return False
    
    if __name__ == '__main__':
    
        testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
        print(binary_search(testlist, 3))
        print(binary_search(testlist, 19))
        print(binary_search2(testlist, 3))
        print(binary_search2(testlist, 19))

    ############################################

    ############################################

    ############################################

  • 相关阅读:
    grunt in webstorm
    10+ Best Responsive HTML5 AngularJS Templates
    响应式布局
    responsive grid
    responsive layout
    js event bubble and capturing
    Understanding Service Types
    To add private variable to this Javascript literal object
    Centering HTML elements larger than their parents
    java5 新特性
  • 原文地址:https://www.cnblogs.com/andy0816/p/12348275.html
Copyright © 2011-2022 走看看