Content
Binary search is a commonly-used search method on sorted arrays/lists. If we need to find element x inside sorted array a, then binary\_search\(a, x\)
can be implemented with Python bisect library.
The bisect module
The bisect
module is called bisect because it uses a basic bisection algorithm: Given element x and sorted array a, the bisect methods returns an index that splits array a
into two parts: one part no larger than x
, the other part no smaller than x
. There are three bisect methods in the bisect library:
bisect\_right
(aliasbisect
): returns the location to insertx
while keepinga
sorted. Ifx
is already ina
, then return the location next to the last appearance ofx
.bisect\_left
: returns the location to insertx
while keepinga
sorted. Ifx
is already ina
, then return the location of the first appearance ofx
.
bisect
module also has three other methods that inserts x
into a
while keeping a sorted
insort\_right
(aliasinsort
): insertsx
into a at locationinsect\_right
insort\_left
: insertsx
into a at locationinsect\_left
Some interesting observations of bisect methods
bisect
methods return insertion points: the index ofx
in a after insertionbisect.bisect
is a short-hand forbisect\_right
and is always the same asbisect\_right
.- When
a
is sorted, andx
is not found ina
,bisect
is also the same asbisect\_left
What if a
is not sorted or a
is not in increasing order?
Looking at the source code of bisect, bisect
implementation doesn't check if a
is properly sorted. Therefore, the behavior of bisect
, bisect\_left
, and bisect\_right
is not defined.