The Wayback Machine - https://web.archive.org/web/20240927154505/https://www.geeksforgeeks.org/python-program-for-binary-search/
Open In App

Python Program for Binary Search (Recursive and Iterative)

Last Updated : 28 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 > 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
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 -> 12 -> 8 -> 4 -> 6 Output: 4 -> 6 -> 8 -> 10 -> 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
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
Number Guessing Game in Python using Binary Search
In the number guessing game, the user selects a number within a defined range and then the program guesses the number. If the number guessed is wrong then the user tells the program that is the actual number is greater than the guessed number or not. Similarly, the program again guesses the number until the actual number is not guessed.Approach: Th
3 min read
Python program to search for the minimum element occurring consecutively n times in a matrix
Given a matrix containing n rows. Each row has an equal number of m elements. The task is to find elements that come consecutively n times horizontally, vertically, diagonally in the matrix. If there are multiple such elements then print the smallest element. If there is no such element then print -1.Examples: Input : n = 4 mat[5][5] 2 1 3 4 5 3 2
4 min read
Python program to Search an Element in a Circular Linked List
A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input: CList = 6->5->4->3->2, find = 3 Output: Element is present Input: CList
3 min read
Python Program for Breadth First Search or BFS for a Graph
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post). Breadth First Search in PythonThe only catch here is, that unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplic
3 min read
Python Program for Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal. Example: Input: n = 4, e = 6 0 -> 1, 0
3 min read
Python Program for Linear Search
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[] using Python. Examples: Input: arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] # Element to Find x = 'J' Output : 9 Explanation: A simple approach is to do a line
4 min read
Python3 Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Example: Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
8 min read
Python program to print number of bits to store an integer and also the number in Binary format
Given an integer, the task is to write a Python program to print the number of bits to store that integer and also print the same number in Binary format. Example: Input: n = 10 Output: Number of bits to store the number: 4 Binary value: 0b1010 Input: n = 120 Output: Number of bits to store the number: 7 Binary value: 0b1111000 The Task can be done
4 min read
Python Program to Check horizontal and vertical symmetry in binary matrix
Given a 2D binary matrix of N rows and M columns. The task is to check whether the matrix is horizontal symmetric, vertical symmetric, or both. The matrix is said to be horizontal symmetric if the first row is the same as the last row, the second row is the same as the second last row, and so on. And the matrix is said to be vertical symmetric if t
3 min read
Python Program for Counting sets of 1s and 0s in a binary matrix
Given a n × m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first and the third cells of the first row. The second
2 min read
Python Program for Binary Insertion Sort
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search. Python Program fo
3 min read
Python program to convert floating to binary
Python doesn't provide any inbuilt method to easily convert floating point decimal numbers to binary number. So, Let’s do this manually. Approach : To convert a floating point decimal number into binary, first convert the integer part into binary form and then fractional part into binary form and finally combine both results to get the final answer
3 min read
Python program to modify the content of a Binary File
Given a binary file that contains some sentences (space separated words), let's write a Python program to modify or alter any particular word of the sentence. Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading
3 min read
Python Program to Generate Random binary string
Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or "1" using randint function from random package. Ap
2 min read
Python Program to Convert any Positive Real Number to Binary string
Given any Real Number greater than or equal to zero that is passed in as float, print binary representation of entered real number. Examples: Input: 123.5 Output: 1 1 1 1 0 1 1 . 1 Input: 0.25 Output: .01 Mathematical Logic along with steps done in programming: Any real number is divided into two parts: The integer part and the Fraction part. For b
4 min read
Python Program to Multiply Two Binary Numbers
Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined functionsMethod 1: Using bin Functions Now, Let's write
2 min read
Python program to add two binary numbers
Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digit
4 min read
Python program to convert Base 4 system to binary number
Given a base 4 number N, the task is to write a python program to print its binary equivalent. Conversion Table: Examples: Input : N=11002233 Output : 101000010101111 Explanation : From that conversion table we changed 1 to 01, 2 to 10 ,3 to 11 ,0 to 00.Input : N=321321 Output: 111001111001Method 1: Take an empty string say resultstr.We convert the
3 min read
Python program to print the binary value of the numbers from 1 to N
Given a positive number N, the task here is to print the binary value of numbers from 1 to N. For this purpose various approaches can be used. The binary representation of a number is its equivalent value using 1 and 0 only. Example for k = 15, binary value is 1 1 1 1 Method 1: Using the Elementary method with recursion. Approach Divide k by 2.Recu
2 min read
Python Program to Count 1's in a sorted binary array
Given a binary array sorted in non-increasing order, count the number of 1's in it.  Examples:  Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0 A simple solution is to linearly traverse the array. The time complexity of the simple solution is O(n). We can u
2 min read
Python program to Represent Negative Integers in binary format
Given a Negative Integer, the task is to write a Python program to convert the integer into binary format. Examples: Input: -14 Output: -1110 Input: -12 Output: -1100 Input: -32 Output: -100000 Let's implement this for the number in different ways : Method 1: Using format specifier 'b' In format specifier type b is used to convert the integer into
1 min read
Python Program to Count number of binary strings without consecutive 1's
Write a Python program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s. Examples: Input: N = 2Output: 3// The 3 strings are 00, 01, 10 Input: N = 3Output: 5// The 5 strings are 000, 001, 010, 100, 101 Recommended: Please solve it on “PRACTICE ” first, before
4 min read