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 insertxwhile keepingasorted. Ifxis already ina, then return the location next to the last appearance ofx.bisect\_left: returns the location to insertxwhile keepingasorted. Ifxis 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): insertsxinto a at locationinsect\_rightinsort\_left: insertsxinto a at locationinsect\_left
Some interesting observations of bisect methods
bisectmethods return insertion points: the index ofxin a after insertionbisect.bisectis a short-hand forbisect\_rightand is always the same asbisect\_right.- When
ais sorted, andxis not found ina,bisectis 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.