So I have the following binary search algorithm that sometimes runs into an infinite loop:
class Solution:
def search(self, nums: List[int], target: int) -> int:
i, j = 0, len(nums)-1
mid = (j+i)//2
while i<j:
if nums[mid] == target:
return mid
if nums[mid] > target:
j = mid
mid = (j+i)//2
else:
i = mid
mid = (j+i)//2
return mid if nums[mid] == target else -1
The correct version has that j = mid+1 and i = mid-1. In certain cases, the code above will run into an infinite loop if the mid pointer is not with in the interval bounded by i and j. Why does that happen, and more importantly, why does having the different assignments prevent that?
An example test case is:
nums = [-1,0,3,5,9,12], target = 2