- Related Questions & Answers
- A program to check if a binary tree is BST or not in C ?
- 0-1 Knapsack Problem in C?
- HTML DOM Anchor search Property
- CSMA/CD with the Binary Exponential Backoff
- Breadth First Search or BFS for a Graph
- Depth First Search or DFS for a Graph
- What is diamond problem in case of multiple inheritance in java?
- Binary array after M range toggle operations?
- HTML DOM Location search Property
- Anti Clockwise spiral traversal of a binary tree?
- An Interesting Method to Generate Binary Numbers from 1 to n?
- All possible binary numbers of length n with equal sum in both halves?
- A Pancake Sorting Problem?
- How to implement the search functionality of a JTable in Java?
- Add n binary strings in C++?

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

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 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.

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

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

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

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

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

Advertisements