线性查找

def linear_search(data_set,value):
    for i in range(len(data_set)):
        if data_set[i]==value:
            return i
    return
print(linear_search([11,22,33,44,55,66],44))

线性查找,时间复杂度O(n)

 

二分查找

从有序列表的候选区data[0:n]开始,通过对待查找的值与候选区中间值的比较,可以使候选区减少一半

def binary_search(li,val):
    low=0
    high=len(li)-1
    while low <= high:
        mid=(low+high)//2
        if li[mid]>val:
            high=mid-1
        elif li[mid]<val:
            low=mid+1
        else:
            return mid
    else:
        return None
li=list(range(1000))
print(binary_search(li,305))

二分查找,循环减半的过程,时间复杂度O(logn)

相关文章:

  • 2021-07-24
  • 2022-03-01
  • 2021-12-07
  • 2022-12-23
  • 2021-08-31
  • 2022-02-07
  • 2022-12-23
猜你喜欢
  • 2021-10-31
  • 2021-06-22
  • 2021-07-15
  • 2021-08-02
  • 2022-12-23
  • 2022-03-05
  • 2021-10-30
相关资源
相似解决方案