Articles

Program to implement binary search in python using function

Program to implement binary search in python using function


In the basic python programming article, we are going to learn:

  • program to implement binary search in python using function

Program to implement binary search in python using function

The program to implement binary search in python using list is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

def binary_search(arr,low,high,element):
    if low <= high:
        mid = (low + high)//2

        if arr[mid] == element:
            return mid
        
        elif arr[mid] > element:
            return binary_search(arr,low,mid-1,element)

        elif arr[mid] < element:
            return binary_search(arr,mid+1,high,element)
    else:
        return -1


if __name__ == "__main__":
    numbers = list(map(int, input("Enter the numbers: ").strip().split()))
    val = int(input("Enter the value to be searched: ").strip())

    numbers.sort()

    idx = binary_search(numbers,0,len(numbers)-1,val)

    if idx == -1:
        print("Element not present in the list")
    else:
        print("Element is present at {} index position.".format(idx))

The output of the binary search program in python using function is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter the numbers: 22 33 44 55 66 77 88 99
Enter the value to be searched: 66
Element is present at 4 index position.

Few important tips about the program

1. The binary search operation is a better algorithm than the linear search algorithm.

2. It only works on lists whose elements are sorted.

3. Here, we find the mid of the list. If the element at the mid position is lesser than the searchable item, the mid becomes the new low for the recursion. If the element at the mid is greater than the searchable item, the mid becomes the new high for the recursion.

4. The time complexity of above binary search in python using list is O(logn).

 

binary search program in python using function snapshot:

binary search program in python using function

This wraps up our session on binary search program in python using function or binary search program in python using function.


Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Data Science Enthusiast
Page Views :    Published Date : Sep 10,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!