Program to search an element using Binary Search in Python

Written by

Himani Kohli

While performing linear search we need to go through each and every node thus it takes more time and hence increases the complexity.

In this python program we are going to use binary search which is an effective way to search an item from the list. In binary search our work become easy as the half of the array is ignored in first comparison. All we have to do is to take out the middle index and compare it with element we need to find.

The main point is that the binary search will perform on sorted array.


  1. The total number of items to enter in the array is asked from the user.
  2. Array is created.
  3. Input the number from the user which we need to search.
  4. A function is created naming “binsearch()”
  5. The function checks if the middle element is greater or smaller than the element that we need to find.
  6. if middle<element then binsearch(A,m,b,q) is called.
  7. if middle>element then binsearch(A,a,m,q) is called.
  8. else if element==middle  
    print “element found”
    Else print” not found”


def binsearch(A, a, b, q):


    if (q> A[m]):

        binsearch(A, m, b, q)

    elif (q<A[m]):

        binsearch(A, a, m, q)

    elif (q== A[m]):

        print("the element is found on index:" )



        print("item not present in the list")

n=int(input("enter the total no. of elements: "r))

print("enter the elements:")


for i in range(n):



print("enter the no. to be searched:")


binsearch(A, 0, n-1, q)



enter the total no. of elements:  6

enter the elements:







enter the no. to be searched:  4

the element is found on index: 4


Program to search an element using Binary Search in Python