Bisect - Array bisection algorithm in Python


Performing sort operations after every insertion on a long list may be expensive in terms of time consumed by processor. The bisect module ensures that the list remains automatically sorted after insertion. For this purpose, it uses bisection algorithm. The module has following functions:

bisect_left()

This method locates insertion point for a given element in the list to maintain sorted order. If it is already present in the list, the insertion point will be before (to the left of) any existing entries. The return value caan be used as the first parameter to list.insert()

bisect_right()

This method is similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.

bisect.insort_left()

This method insert given value in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x)

bisect.insort_right()

bisect.insort()

Bothe methods are similar to insort_left(), but inserting given value in the list after any existing entries of same value.

Example

>>> nums = [45,21,34,87,56,12,5,98,30,63]
>>> nums.sort()
>>> nums
[5, 12, 21, 30, 34, 45, 56, 63, 87, 98]
>>> import bisect
>>> p = bisect.bisect_left(nums,50)
>>> p
6
>>> nums.insert(p,50)
>>> nums
[5, 12, 21, 30, 34, 45, 50, 56, 63, 87, 98]
>>> bisect.insort(nums, 29)
>>> nums
[5, 12, 21, 29, 30, 34, 45, 50, 56, 63, 87, 98]

Updated on: 30-Jul-2019

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements