python binary search

高洛峰
Release: 2016-12-19 16:32:33
Original
2051 people have browsed it

The following is a binary search code implemented in 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)
Copy after login

The running test results:

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


For more python binary search related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template