A Problem in Many Binary Search Implementations?

We know that the binary search algorithm is better than the linear search algorithm. This algorithm takes O(log n) amount of time to execute. Though most of the cases the implemented code has some problem. Let us consider one binary search algorithm function like below −


int binarySearch(int array[], int start, int end, int key){
   if(start <= end){
      int mid = (start + end) /2); //mid location of the list
      if(array[mid] == key)
         return mid;
      if(array[mid] > key)
         return binarySearch(array, start, mid-1, key);
         return binarySearch(array, mid+1, end, key);
   return -1;

This algorithm will work fine until the start and end reaches a large number. If the (start + end) is exceeding the value of 232 – 1 then it may return one negative number after wrapping up. And as the negative numbers are not supported as array index, then it may cause some problem.

To overcome this problem, there are few different ways.

Method 1

int mid = start + ((end - start) / 2)

The second method will work only in Java as C or C++ has no >>> operator.

Method 2 (Java only)

int mid = (start + end) >>> 1

As >>> is not supported in C or C++, then we can use the following method.

Method 3

int mid = ((unsigned int) low + (unsigned int) high) >> 1