+ 1

binary search for array with EVEN number of elements...

Hi there In the binary search algorithm, as you know, we need to select the middle element of the array. It’s obvious for an array with odd number of elements. for example in arr[5], the middle element would be arr[2] (- - * - - ) . now I wanna ask what happens when the number of elements is EVEN ? arr[4] for instance !? (- - - -) Already thanks for replies🙏🏻

27th Feb 2021, 8:12 PM
Ali Hosseinzadeh
Ali Hosseinzadeh - avatar
2 odpowiedzi
+ 3
you have to arbitrary choose one of the two middle elements... usually we use the result of length/2 casted to integer (floor/integer division)...
27th Feb 2021, 8:14 PM
visph
visph - avatar
0
correct way to calculate middle value in binary search is: low+((high-low)/2) its work for both ( if array is of even size or odd size)
21st Nov 2024, 11:25 AM
afsar jahan
afsar jahan - avatar