Search code examples
pythonalgorithmbinary-search

In binary search, how does computer choose mid point and when there is only two elements left


I've read some stackoverflow questions and other blogs about this matter.

Most of them explain to choose mid point by using:

1. low + (high - low)/2
2. (low + high)/2, round down to integer.

from Deciding mid in binary search and https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/binary-search

None of them quite make sense.

say I have a list in the form

lst = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]

using 1. midpoint = 46.5 and by using 2. midpoint = 50.5, rounded down to 50.

both midpoint isn't even in my list.

Furthermore when there are only 2 element, which one does it choose as a midpoint?


Solution

  • The low and the high variables do not refer to the elements of the list or the array. They refer to the indices of the list or array. So the middle element will not be given by: low + (high - low)/2 or (low + high)/2 (round down to an integer) but rather by lst[low + (high - low)/2] or lst[(low + high)/2]