Python二分查找

代码:

时间复杂度:O(log2n)

#!/usr/bin/env python
#coding:utf-8
import copy
from copy import deepcopy

'''
def erfen(x,n,l):

    
    
    for i in range(n):
        mid = len(l)//2
        if (x == l[mid]):
            print(mid)
            break
        elif (x < l[mid]):
            for i in range(mid,n):
                l.pop(l[i])
                erfen(x, mid, l)
        elif (x > l[mid]):
            for i in range(0,mid):
                l.pop(l[i])
                erfen(x, mid, l)
                
        else:
            for i in ll:
                if (l[mid+1] == ll[i]):
                    aa = (-1)-(mid+1)
                    print(aa)
                    break

if __name__=="__main__":
    x = int(input())
    n = int(input())
    s = input().split()
    l = []
    
    for i in range(n):
        l.append(int(s[i]))
        
    global ll
    ll = deepcopy(l)
    
    for i in range(n):
        if(x == ll[i]):
            print(i)
        else:
            erfen(x, n, l)
'''

def search_erfen(x,l):
    start = 0
    end = len(l)
    
    while(start<end):
        mid = (start+end)//2
        if (l[mid]>x):
            end = mid
        elif(l[mid]<x):
            start = mid+1
        elif(l[mid == x]):
            return mid
    return -1


if __name__=="__main__":
    x = 5
    l=[1,3,4,6,7,9]
    print(search_erfen(x, l))

 

 

 

 

dd

posted @ 2016-09-18 09:35  航飞冲天  阅读(213)  评论(0编辑  收藏  举报