Binary Search code

By | May 24, 2014

Binary Search finds the position of a specified value (key) in a sorted array.In each step it discards half of the elements to search , thus the worst case running time of binary search is O(log n).Believe it or not 80 out of 100 of the programmers fail to write the correct code for binary search which doesn’t have a single bug.

Binary search follows these simple steps :

  1. Compare the middle element of the array with key if middle element is same as key return the index of the middle else go to step 2
  2. if middle element greater than key  binary search for the key in the left half of the array (start to middle-1) , if its less  than key binary search for the key in the right half of the array (middle+1 to end) .
  3. repeat this till the size of array to search reduces to zero.

Here’s the C++ code for binary search algorithm.

Leave a Reply

Your email address will not be published. Required fields are marked *