When are bisect_left and bisect_right not equal?

后端 未结 5 1294
半阙折子戏
半阙折子戏 2021-02-02 09:17

In my understanding, bisect_left and bisect_right are two different ways of doing the same thing: bisection, one coming from the left and the other coming from the right. Thus,

5条回答
  •  佛祖请我去吃肉
    2021-02-02 09:46

    To me this interpretation of bisect_left/bisect_right makes it more clear:

    • bisect_left returns the largest index to insert the element w.r.t. <
    • bisect_right returns the largest index to insert the element w.r.t. <=

    For instance, if your data is [0, 0, 0] and you query for 0:

    • bisect_left returns index 0, because that's the largest possible insert index where the inserted element is truly smaller.
    • bisect_right returns index 3, because with "smaller or equal" the search advances through identical elements.

    This behavior can be simplified to:

    • bisect_left would insert elements to the left of identical elements.
    • bisect_right would insert elements to the right of identical elements.

提交回复
热议问题