Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating midpoint index in binary search

Tags:

c

search

So, the correct way of calculating mid in a binary search is mid = low + ((high - low) / 2) in order to handle overflow errors.

My implementation uses unsigned 64 bit variables and I don't ever see a situation where my arrays get so big so as to cause an overflow. Do I still need use the above implementation or can I use mid = (low + high) / 2

What's best practice here?

like image 599
user1033777 Avatar asked Jan 13 '14 20:01

user1033777


People also ask

What is the mid value in binary search?

Given a sorted array, we find the middle-most element and check the element with the key. If the middle-most element is equal to key, we've found the key. If the middle-most element is greater than the key, we search on the left half of the middle-most element, else we search on the right half.

How do you calculate mid?

Measure the distance between the two end points, and divide the result by 2. This distance from either end is the midpoint of that line. Alternatively, add the two x coordinates of the endpoints and divide by 2. Do the same for the y coordinates.

What is low and high in binary search?

The value of low cannot be greater than high; this means that the key is not in the vector. So, the algorithm repeats until either the key is found or until low > high, which means that the key is not there. The following function implements this binary search algorithm.


1 Answers

If there is no possibility of overflow, the overflow-safe way of computing the midpoint is technically unnecessary: you can use the unsafe formula if you wish. However, it's probably a good idea to keep it there anyway, in case that your program gets modified some day to break your assumptions. I think that adding a single CPU instruction to make your code future-proof is a great investment in maintainability of your code.

like image 139
Sergey Kalinichenko Avatar answered Sep 19 '22 13:09

Sergey Kalinichenko