Binary search algorithm in python

前端 未结 14 928
别那么骄傲
别那么骄傲 2020-12-01 11:23

I am trying to implement the binary search in python and have written it as follows. However, I can\'t make it stop whenever needle_element is larger than the largest elemen

相关标签:
14条回答
  • 2020-12-01 11:57

    Why not use the bisect module? It should do the job you need---less code for you to maintain and test.

    0 讨论(0)
  • 2020-12-01 11:57

    It returns the index of key in array by using recursive.

    round() is a function convert float to integer and make code fast and goes to expected case[O(logn)].

    A=[1,2,3,4,5,6,7,8,9,10]
    low = 0
    hi = len(A)
    v=3
    def BS(A,low,hi,v):
        mid = round((hi+low)/2.0)
        if v == mid:
            print ("You have found dude!" + " " + "Index of v is ", A.index(v))
        elif v < mid:
            print ("Item is smaller than mid")
            hi = mid-1
            BS(A,low,hi,v)
        else :
            print ("Item is greater than mid")
            low = mid + 1
            BS(A,low,hi,v)
    BS(A,low,hi,v)
    
    0 讨论(0)
提交回复
热议问题