Binary Search
Asked to find the index of a value within a sorted list of numbers. That means binary search right. Point of reference here is that I have never had to do this in a work setting because the data is never ordered or kept in order. Uniqueness sure, but the maintaining the order of a list is a painful insert and is something that haven't had to do ever. On to the solution below.
Recursive implementation
Point of interests here
- Is first test for is the input list empty then return -1
- Is the current midpoint the value you are looking for then return it
- Subpoint is that the start point keeps shifting on the right side as the list is split up so you have to add them up
- Finally check with an if statement on which side of the current list you should be looking if the value is less than then the left side, greater than then the right side
def find_value(target_value: int, start_point: int, elements: list[int]) -> int:
if len(elements) == 0:
return -1
midpoint = len(elements) // 2
compare_value = elements[midpoint]
if compare_value == target_value:
return midpoint + start_point
if compare_value < target_value:
return find_value(target_value, midpoint + start_point + 1, elements[midpoint + 1:])
return find_value(target_value, start_point, elements[:midpoint])
Results
ic| find_value(16, 0, [2,3,5,8,9,13,14,15,16,35]): 8