How to Do a Binary Search in Python

How to Do a Binary Search in Python

In this python tutorial, we would like to share with you the following .Binary Search .Algorithm Binary Search .Python Program for Binary Search .Write a python program to implement binary search using recursion

In this python tutorial, we would like to share with you the following:

  • Binary Search
  • Algorithm Binary Search
  • Python Program for Binary Search
  • Write a python program to implement binary search using recursion

Binary Search is applied on the sorted array or list of large size. It’s time complexity of O(log n) makes it very fast as compared to other sorting algorithms. To use binary search on a collection, the collection must first be sorted.

Implement binary search following the below steps:

  1. Start with the middle element of the given list:
    • If the target value is equal to the middle element of the array, then return the index of the middle element.
    • Otherwise, compare the middle element with the target value,
      • If the target value is greater than the number in the middle index, then pick the elements to the right of the middle index, and start with Step 1.
      • If the target value is less than the number in the middle index, then pick the elements to the left of the middle index, and start with Step 1.
  2. If a match is found, return the index of the element matched.
  3. Otherwise, return -1
# Binary search function
def binarySearchAlgo(xlist, key):

    a = 0
    b = len(xlist)
    while a < b:
        c = (a + b)//2
        if xlist > key:
            b = c
        elif xlist < key:
            a = c + 1
        else:
            return c
    return -1

# input a list of elements
xlist = input('Enter the sorted list of numbers: ')

#split a element
xlist = xlist.split()
xlist = [int(x) for x in xlist]

# search for in list
key = int(input('The number to search for: '))

# call binary search function
index = binarySearchAlgo(xlist, key)
if index < 0:
    print('{} was not found.'.format(key))
else:
    print('{} was found at index {}.'.format(key, index))

After executing the program, the output will be:

Enter the sorted list of numbers:  1 2 3 4 5 6 7 8 9
The number to search for:  8
8 was found at index 7.

Write a python program to implement binary search using recursion

# Python code for recursive binary search

# Returns index of key in xlist if present, else -1 
def binarySearch (arr, l, r, x): 

    # Check base case 
    if r >= l: 

        mid = l + (r - l)//2

        # If element is present at the middle itself 
        if arr[mid] == x: 
            return mid 

        # If element is smaller than mid, find in left sub array
        elif arr[mid] > x: 
            return binarySearch(arr, l, mid-1, x) 

        # Otherwise find the element in right subarray 
        else: 
            return binarySearch(arr, mid+1, r, x) 

    else: 
        # Element is not present in the list 
        return -1

# input a list of elements
xlist = input('Enter the sorted list of numbers: ')

#split a element
xlist = xlist.split()
xlist = [int(x) for x in xlist]

# search for in list
key = int(input('The number to search for: '))

# Function call 
result = binarySearch(xlist, 0, len(xlist)-1, key) 

if result != -1: 
      print('{} was found at index {}.'.format(key, result))
else: 
    print('{} was not found.'.format(key))

After executing the program, the output will be:

Enter the sorted list of numbers:  1 2 3 4 5 6 7 8
The number to search for:  6
6 was found at index 5.

python programming

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Guide to Python Programming Language

Guide to Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Learn Python Programming

Learn Python Programming

Python Programming & Data Handling

Python Programming & Data Handling

Learn Programming With Python In 100 Steps

Description We love Programming. Our aim with this course is to create a love for Programming. Python is one of the most popular programming languages. Python offers both object oriented and structural programming features. We take an hands-on...