What are python's equivalents of std::lower_bound and std::upper_bound C++ algorithms?
Asked Answered
U

2

62

Does python provide functions for performing binary search on sorted lists, analogous to the std::lower_bound and std::upper_bound algorithms of the C++ Standard Library?

Uncinus answered 17/6, 2016 at 5:43 Comment(1)
See also: stackoverflow.com/questions/212358Snuffer
U
88

Those functions are located in the bisect module:

  • bisect.bisect_left(a, x, lo=0, hi=len(a)) is the analog of std::lower_bound().

  • bisect.bisect_right(a, x, lo=0, hi=len(a)) is the analog of std::upper_bound().

Note: there is also a function bisect() which is an alias for bisect_right().

Uncinus answered 17/6, 2016 at 5:43 Comment(0)
T
0

There is also sortedcontainers package in python, which also has bisect_left and bisect_right. https://grantjenks.com/docs/sortedcontainers/sortedlist.html

This could be handy if you don't want to maintain the list sorted yourself (e.g. insertion).

Tableware answered 6/10, 2022 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.