SIDEBAR

Algorithms. Binary Search

0 comments
янв 05 2018
Post's featued image.

#A FUNCTION FOR THE BINARY SEARCH ALGORITHM || O (log n)

def binary_search(array, item):
    low = 0
    high = len(array)-1
    
   
    while low<=high:
        mid = (low+high) // 2
        guess = array[mid]
        if guess ==item:
            print (guess)
            return guess
        if guess > item:
            print (guess)
            high = mid-1
        else:
            print (guess)
            low = mid+1
    return None    

#DATA TO CHECK THE ALGORITHM

list_to_search = (range(0, 4000000000))
item_to_search = 2500000

#EXECUTE THE ALGORITHM

binary_search(list_to_search, item_to_search)
1999999999
999999999
499999999
249999999
124999999
62499999
31249999
15624999
7812499
3906249
1953124
2929686
2441405
2685545
2563475
2502440
2471922
2487181
2494810
2498625
2500532
2499578
2500055
2499816
2499935
2499995
2500025
2500010
2500002
2499998
2500000
2500000

Submit a Comment