列表查找的两种方法

列表查找:从列表中查找指定元素

输入:列表、待查找元素

输出:元素下标或未找到元素

列表查找的两种方法:

  • 顺序查找
    • 从列表的第一个元素开始,顺序进行搜索,直到找到为止。
  • 二分查找
    • (大前提有序)从有序列表的候选区[0:n]开始,通过对待查找的值与候选区中间值的比较,可以使候选区减少一半。

1.顺序查找代码:(时间复杂度为O(n))

def linear_search(data_set, value):
    for i in range(len(data_set)):
        if value == data_set[i]:
            return i
    return 

2.二分查找代码:(时间复杂度为O(logn))

def binary_search(data_set, low, high, val):
    
    while low <= high:
        mid = (low + high) // 2
        if data_set[mid] == val:
            return mid
        elif val > data_set[mid]:   # 值在列表右边
            low = mid + 1
        else:       # 值在列表左边
            high = mid -1
    return 

递归版本的二分查找

def binary_search2(data_set, low, high, val):
    if low <= high:
        mid = (low+high) // 2
        if data_set[mid] == val:
            return mid
        elif val < data_set[mid]:
            binary_search2(data_set, low, mid-1, val)
        else:
            binary_search2(data_set, mid+1, high, val)
    else:
        return 

猜你喜欢

转载自www.cnblogs.com/Xuuuuuu/p/10808392.html