- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 −

## Example

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 2^{32} – 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

- Related Articles
- Binary Search
- Binary Search a String in C++
- Binary Search in C++
- Binary search in C#
- Binary search in Java.
- Balance a Binary Search Tree in c++
- Implementing a Binary Search Tree in JavaScript
- Binary Search Tree in Javascript
- Binary Search in C++ program?
- Binary Search (bisect) in Python
- Binary Search program in JavaScript
- Explain Binary Search in Python
- C++ Program to Search for an Element in a Binary Search Tree
- Binary Search Tree - Search and Insertion Operations in C++
- Search in an array with Binary search using JavaScript