MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / upper_bound

Function upper_bound

searches/binary_search.py:293–310  ·  view source on GitHub ↗

Returns the index of the first element strictly greater than the item. :param sorted_collection: The sorted list to search. :param item: The item to find the upper bound for. :return: The index where the item can be inserted after all existing instances.

(sorted_collection: list[int], item: int)

Source from the content-addressed store, hash-verified

291 return left
292
293 def upper_bound(sorted_collection: list[int], item: int) -> int:
294 """
295 Returns the index of the first element strictly greater than the item.
296
297 :param sorted_collection: The sorted list to search.
298 :param item: The item to find the upper bound for.
299 :return: The index where the item can be inserted after all existing instances.
300 """
301 left = 0
302 right = len(sorted_collection)
303 while left < right:
304 midpoint = left + (right - left) // 2
305 current_item = sorted_collection[midpoint]
306 if current_item <= item:
307 left = midpoint + 1
308 else:
309 right = midpoint
310 return left
311
312 left = lower_bound(sorted_collection, item)
313 right = upper_bound(sorted_collection, item)

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected