Binary Search (bisect) in Python

PythonServer Side ProgrammingProgramming

Here we will see the bisect in Python. The bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function.

We will see three different task using bisect in Python.

Finding first occurrence of an element

The bisect.bisect_left(a, x, lo = 0, hi = len(a)) this function is used to return the left most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist.

Example

from bisect import bisect_left
def BinSearch(a, x):
   i = bisect_left(a, x)
   if i != len(a) and a[i] == x:
      return i
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(4)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("First occurrence of", x, "is at position", pos)

Output

First occurrence of 4 is at position 2

Finding greatest value which is smaller than x

Using the bisect_left option, we can get the greater value, which is smaller than the x (key).

Example

from bisect import bisect_left
def BinSearch(a, x):
   i = bisect_left(a, x)
   if i :
      return i-1
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(8)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("Larger value, smaller than", x, "is at position", pos)

Output

Larger value, smaller than 8 is at position 4

Finding right most occurrence of x

The bisect.bisect_right(a, x, lo = 0, hi = len(a)) this function is used to return the right most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist.

Example

from bisect import bisect_right
def BinSearch(a, x):
   i = bisect_right(a, x)
   if i != len(a) + 1 and a[i-1] == x:
      return i-1
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(36)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("Right most occurrence of", x, "is at position", pos)

Output

Right most occurrence of 36 is at position 9
raja
Published on 20-Aug-2019 11:20:07
Advertisements