I’m looking for algorithm with an average case performance of O(log(N)), to extract the elements are between (or equal to) a min and a max value from a sorted list.
The issue being that since the the min and max values may not actually be in the list, or perhaps even repeated, a binary search won’t do. Ternary search seems to be closer to what I seek, but I haven’t been able to create a function that does what I see based on ternary search so far.
For example, the input:
list=[1,2,3,4,5,6,7], min=3, max=6
Should return [3,4,5,6]. Likewise,
list=[500,757,2412,10000,123123], min = 600, max = 5000
Should return [757,2412].
This could also be done in python less efficiently using:
def withinRange(values,min,max):
return [val for val in sorted(values) if val <= max and val >= min]
The operation is called enough that a O(log(N)) is very much preferred, and the sorting will only be done once.
This seems to work:
The complexity is something like 2log(N) which is O(log(N)). Also note that
bisectmay use a C implementation forbisectwhich will be faster than anything you can write in pure-python, so a pure-python solution will probably be slower even if doing a bit less comparisons.You could optimize slightly the search for
jpassing theloparameter tobisect: