Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a binary search for a range of the same value?

I have a sorted list of numbers and I need to get it return the range of index that the number appears. My list is:

daysSick = [0, 0, 0, 0, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 11, 15, 24]

If I searched 0, I need to return (0, 3). Right now I can only get it to find the spot of one number! I know how to do the binary search, but I am stuck how to make it move up and down from the position to find the other same values!

low = 0
high = len(daysSick) - 1
while low <= high :
    mid = (low + high) // 2
    if value < daysSick[mid]:
        high = mid - 1
    elif value > list[mid]:
        low = mid + 1
    else:
        return mid

1 Answers

You may use Python's bisection routines from the stdlib:

>>> daysSick = [0, 0, 0, 0, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 11, 15, 24]
>>> from bisect import bisect_left, bisect_right
>>> bisect_left(daysSick, 3)
6
>>> bisect_right(daysSick, 3)
9
>>> daysSick[6:9]
[3, 3, 3]
like image 141
wim Avatar answered Jan 26 '26 12:01

wim