欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

python二分法查找

程序员文章站 2022-03-18 15:04:47
...
下面是一段用Python实现的二分法查找代码
#encoding=utf-8  
  
import sys  
  
def search2(a,m):  
    low = 0  
    high = len(a) - 1  
    while low<=high:  
        mid = (low + high)/2  
        midval = a[mid]  
  
        if midval<m:  
            low = mid + 1  
        elif midval>m:  
            high = mid-1  
        else:  
            print mid  
            return mid  
    print -1  
    return -1  
  
if __name__ == "__main__":  
  
    a = [int(i) for i in list(sys.argv[1])]  
    m = int(sys.argv[2])  
    search2(a,m)

运行测试结果:

shao@ubuntu:~/tmp$ python test_search2.py 123456789 4  
3


更多python二分法查找相关文章请关注PHP中文网!

相关标签: 二分法查找