Open In App

Python Program for Binary Search (Recursive and Iterative)

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In a nutshell, this search algorithm takes advantage of a collection of elements that is already sorted by ignoring half of the elements after just one comparison. 

  1. Compare x with the middle element.
  2. If x matches with the middle element, we return the mid index.
  3. Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray after the mid element. Then we apply the algorithm again for the right half.
  4. Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the left half.

Python Program for Binary Search Using Recursive

Python3




# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
 
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
 
    # Check base case
    if high >= low:
 
        mid = (high + low) // 2
 
        # If element is present at the middle itself
        if arr[mid] == x:
            return mid
 
        # If element is smaller than mid, then it can only
        # be present in left subarray
        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)
 
        # Else the element can only be present in right subarray
        else:
            return binary_search(arr, mid + 1, high, x)
 
    else:
        # Element is not present in the array
        return -1
 
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
 
# Function call
result = binary_search(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")


Output

Element is present at index 3

Time Complexity: O(log n)

Auxiliary Space: O(logn)     [NOTE: Recursion creates Call Stack]

Python Program for Binary Search Using Iterative 

Python3




# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0
 
    while low <= high:
 
        mid = (high + low) // 2
 
        # If x is greater, ignore left half
        if arr[mid] < x:
            low = mid + 1
 
        # If x is smaller, ignore right half
        elif arr[mid] > x:
            high = mid - 1
 
        # means x is present at mid
        else:
            return mid
 
    # If we reach here, then the element was not present
    return -1
 
 
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
 
# Function call
result = binary_search(arr, x)
 
if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")


Output

Element is present at index 3

Time Complexity: O(log n)

Auxiliary Space: O(1)

Python Program for Binary Search Using the built-in bisect module

Step by step approach:

  • The code imports the bisect module which provides support for binary searching.
  • The binary_search_bisect() function is defined which takes an array arr and the element to search x as inputs.
  • The function calls the bisect_left() function of the bisect module which finds the position of the element in the sorted array arr where x should be inserted to maintain the sorted order. If the element is already present in the array, this function will return its position.
  • The function then checks if the returned index i is within the range of the array and if the element at that index is equal to x.
  • If the condition is true, then the function returns the index i as the position of the element in the array.
  • If the condition is false, then the function returns -1 indicating that the element is not present in the array.
  • The code then defines an array arr and an element x to search.
  • The binary_search_bisect() function is called with arr and x as inputs and the returned result is stored in the result variable.
  • The code then checks if the result is not equal to -1, indicating that the element is present in the array. If true, it prints the position of the element in the array.
  • If the result is equal to -1, then the code prints a message that the element is not present in the array.

Python3




import bisect
  
def binary_search_bisect(arr, x):
    i = bisect.bisect_left(arr, x)
    if i != len(arr) and arr[i] == x:
        return i
    else:
        return -1
  
  
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
  
# Function call
result = binary_search_bisect(arr, x)
  
if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")


Output

Element is present at index 3

Time Complexity: O(log n)

Auxiliary Space: O(1)
 



Previous Article
Next Article

Similar Reads

Python Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Python Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Python] Python Program for Iterative Merge SortThe provided Python code demonstrates the recursive implementation of the Merge Sort algorithm. Merge Sort divides an array into smaller subarrays, sorts them, and then merges them back together to achieve a
2 min read
Python Program for Iterative Quick Sort
The code consists of two main functions: partition and quickSortIterative, along with a driver code to test the sorting process. The partition function is used for the process of partitioning a given subarray into two parts - elements less than or equal to the chosen pivot (arr[h]) on the left and elements greater on the right. It operates within t
4 min read
Fibonacci Series Program In Python Using Iterative Method
Fibonacci series is a series where each number is the sum of its two previous numbers. In this article, we are going to generate Fibonacci series in Python using Iterative methods. We will be covering both the loops i.e. for loop and while loop. In this article, we will be covering all the concepts related to the topic with clear and concise exampl
4 min read
Iterative Boundary Traversal of Complete Binary tree
Given a complete binary tree, traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root. Example: Input: 18 / \ 15 30 / \ / \ 40 50 100 20 Output: 18 15 40 50 100 20 30 Approach: Traverse left-most nodes of the tree from top to down. (Left boundary)Traverse bottom-most level of the tree from left to rig
9 min read
Python Program for Recursive Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Python Program for Recursive Insertion Sort for Iterative algorithm for insertion sortAlgorithm // Sort an arr[] of size ninsertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i-1] Python Code
4 min read
Python Program For Recursive Selection Sort For Singly Linked List - Swapping Node Links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input: 10 -&gt; 12 -&gt; 8 -&gt; 4 -&gt; 6 Output: 4 -&gt; 6 -&gt; 8 -&gt; 10 -&gt; 12 In Selection Sort, we first find
4 min read
Python - Iterative Pair Pattern
Sometimes, while working with Python, we can have problem in which we need to perform the pattern construction or iterative pair string in which second element keeps increasing. This kind of problem can have application in day-day programming and school programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using lo
3 min read
Iterative Letter Combinations of a Phone Number
Given an integer array containing digits from [0, 9], the task is to print all possible letter combinations that the numbers could represent. A mapping of digit to letters (just like on the telephone buttons) is being followed. Note that 0 and 1 do not map to any letters. All the mapping are shown in the image below: Example: Input: arr[] = {2, 3}
7 min read
Binary Search (bisect) in Python
Binary Search is a technique used to search element in a sorted list. In this article, we will looking at library functions to do Binary Search.Finding first occurrence of an element. bisect.bisect_left(a, x, lo=0, hi=len(a)) : Returns leftmost insertion point of x in a sorted list. Last two parameters are optional, they are used to search in subli
2 min read