Open In App

Binary Search (bisect) in Python

Last Updated : 04 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 sublist.

 

Python3




# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
 
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    else:
        return -1
 
= [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("First occurrence of", x, "is present at", res)


Output: 

First occurrence of 4 is present at 2

 

Finding greatest value smaller than x. 
 

Python3




# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
 
def BinarySearch(a, x):
    i = bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
 
# Driver code
= [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
    print("No value smaller than ", x)
else:
    print("Largest value smaller than ", x, " is at index ", res)


Output: 

Largest value smaller than  7  is at index  3

 

Finding rightmost occurrence
 

bisect.bisect_right(a, x, lo=0, hi=len(a)) Returns rightmost insertion point of x in a sorted list a. Last two parameters are optional, they are used to search in sublist.

 

Python3




# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
 
def BinarySearch(a, x):
    i = bisect_right(a, x)
    if i != 0 and a[i-1] == x:
        return (i-1)
    else:
        return -1
 
= [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
    print(x, "is absent")
else:
    print("Last occurrence of", x, "is present at", res)


Output: 

Last occurrence of 4 is present at 3

 

Please refer Binary Search for writing your own Binary Search code.
Reference : 
https://docs.python.org/3/library/bisect.html
 



Previous Article
Next Article

Similar Reads

Bisect Algorithm Functions in Python
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module "bisect" which allows keeping the list in sorted order after the insertion of each element. This is essential as this reduces overhead time required to
5 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read