Python Program Binary Search

By | September 6, 2023

Python Program Binary Search – In this program, a sorted list is given and a target item to be searched in the list.

 

Source Code of Python Binary Search Program


binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid  # Target found
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1  # Target not found

arr = [19, 67, 80, 96, 108]
target = 960
index = binary_search(arr, target)
if index==-1:
    print("Target item ", target, " not found in given list: ",arr)
else:
    print("Target item ", target, " found on index = ",index," in given list: ",arr)


Output:
Target item found on index =  3  in given list:  [19, 67, 80, 96, 108]

Output:
Target item  960  not found in given list:  [19, 67, 80, 96, 108]



Loading

Leave a Reply

Your email address will not be published. Required fields are marked *