Binary search algorithm issue in Python book

#1

In page 152 of the Elements of Programming Interviews in Python, there is an algorithm of binary search by Jon Bentley. The function is named as bsearch. Line 4 of the algorithm is written as M = (L + U) // 2. But after the algorithm, when discussing the overflow issue of the algorithm, The line is written as M = (L + U) / 2. The correct version of the code is written as M = L + (U - L) / 2. Is / the right operator to use here?

In Python 3, for an array with odd length the expression will return a fraction for M. As M is the index of the array it can’t be a fraction. The // operator feels like the right one. Can anyone confirm this?

0 Likes