Python二分検索

780 ワード

def bsearch(l = [], a = 0 ,b = 0,t = 0):
 
    if(a>b):
        print 'can\'t find\t'
    elif(a<b):
        middle = (a + b) / 2
        if l[middle] == t:
            print middle
        elif l[middle] > t:
            bsearch(l,a,middle-1,t)
        else:
            bsearch(l,middle+1,b,t)
    else:
        if l[a] == t:
            print a
        else:
            print 'can\'t find'

if __name__ == '__main__':
    l = [11,2,23,4,51,6,27,8]
    l.sort(cmp=None, key=None, reverse=False);
    t = int(raw_input("Enter the digit you want search:"))
    bsearch(l,0,len(l)-1,t)