Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Program for Binary Search



In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement − We will be given a sorted list and we need to find an element with the help of a binary search.

Algorithm

  • Compare x with the middle element.

  • If x matches with the middle element, we return the mid index.

  • Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for the right half.

  • Else (x is smaller) recur for the left half

Recursive Algorithm

Example

def binarySearchAppr (arr, start, end, x):
# check condition
if end >= start:
   mid = start + (end- start)//2
   # If element is present at the middle
   if arr[mid] == x:
      return mid
   # If element is smaller than mid
   elif arr[mid] > x:
      return binarySearchAppr(arr, start, mid-1, x)
   # Else the element greator than mid
   else:
      return binarySearchAppr(arr, mid+1, end, x)
   else:
   # Element is not found in the array
      return -1
arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'
result = binarySearchAppr(arr, 0, len(arr)-1, x)
if result != -1:
   print ("Element is present at index "+str(result))
else:
print ("Element is not present in array")

Iterative Algorithm

Example

 Live Demo

def binarySearchAppr (arr, start, end, x):
# check condition
   if end >= start:
      mid = start + (end- start)//2
      # If element is present at the middle
      if arr[mid] == x:
      return mid
      # If element is smaller than mid
      elif arr[mid] > x:
      return binarySearchAppr(arr, start, mid-1, x)
      # Else the element greator than mid
      else:
      return binarySearchAppr(arr, mid+1, end, x)
   else:
      # Element is not found in the array
      return -1
arr = sorted(['t','u','t','o','r','i','a','l'])
   x ='r'
   result = binarySearchAppr(arr, 0, len(arr)-1, x)
if result != -1:
   print ("Element is present at index "+str(result))
else:
   print ("Element is not present in array")
Element is present at index 4

Conclusion

In this article, we learned about the approach to apply Binary Search.

Updated on: 2019-09-25T12:50:04+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements