dichotomy problem
Implementing dichotomy is not very difficult. But some implementation methods on the Internet are wrong. The problem lies in terminating the loop and judging mid. The implementation code is as follows:
def bsearch(arr,v):
left,right=0,len(arr)
while left <= right:
mid = (left + right) // 2
if arr[mid] == v:
return mid
elif arr[mid] > v:
right = mid-1
else:
left = mid+1
else:
return -1
Question 1: Termination Conditions
The termination condition should be right>=left. Some implementation methods use right>left, which may cause an infinite loop
Question 2: right=mid-1
right=mid is incorrect when changing upper and lower bounds. It should be right=mid-1. In the same way, left should be mid+1.
It is recommended to use the dichotomy in bisect, which is fast and can return qualified subscripts.