How to implement the binary search algorithm in Python

2 Answers

0 votes
def binary_search(arr, to_find): 
    right = len(arr) - 1
    left = 0
    while left <= right: 
        mid = (int)(left + (right - left) / 2)
        if arr[mid] == to_find: 
            return mid 
        elif arr[mid] < to_find: 
            left = mid + 1
        else: 
            right = mid - 1
    return -1

  
arr = [ 2, 3, 6, 7, 12, 15, 17, 19 ] 
to_find = 7
  
result = binary_search(arr, to_find) 
  
if result != -1: 
    print("Found at index: % d" % result)
else: 
    print("Not found")



'''
run:

Found at index:  3

'''

 



answered Aug 5, 2019 by avibootz
edited Aug 5, 2019 by avibootz
0 votes
def binary_search(lst, n, ln):
    start = 0
    end = ln - 1
    mid = 0
 
    while start <= end:
        mid = (end + start) // 2
        if lst[mid] < n:
            start = mid + 1
        elif lst[mid] > n:
            end = mid - 1
        else:
            return mid
    return -1
 
     
lst = [1, 2, 3, 7, 9, 11, 17, 20, 40]
 
result = binary_search(lst, 9, len(lst))
 
if result == -1:
    print("Element not found")
else:
    print("Element found at index", result)
    
     
     
     
     
'''
run:
     
Element found at index 4
     
'''

 



answered Jan 18, 2022 by avibootz
...