zoukankan      html  css  js  c++  java
  • 二分法查找

    1.用函数来进行二分查找:

      lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]

    def run(left,right,n,count):
    middle=(left+right)//2
    if n >lst[middle]:
    left=middle+1
    elif n < lst[middle]:
    right=middle-1
    else:
    return (middle,'找到了,共计查找了%s次' % count)
    return run(left,right,n,count+1)
    print(run(0,len(lst)-1,11,1))

    2.普通方法:

    lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]
    n=11 #要查询的数
    left=0
    right=len(lst)-1
    count=0
    while left <= right:
    count+=1
    middle = (left + right) // 2
    if n > lst[middle]:
    left=middle+1
    elif n < lst[middle]:
    right=middle-1
    else:
    print('索引为%s,共计查询了%s次' % (middle,count))
    break
    else:
    print('不存在')


  • 相关阅读:
    du
    date
    echo
    redis的多实例
    redis相关配置
    mariadb的安装与主从复制
    11.Flask-钩子函数
    Python之Linux下的virtualenv&&virtualenvwrapper
    Linux的防火墙概念
    安装ipython解释器
  • 原文地址:https://www.cnblogs.com/quzq/p/9394483.html
Copyright © 2011-2022 走看看