Binary Search in C++

Binary Search is a method to search through a sorted container in order to find a particular value.

Remember that one “Guess the Number” game? Let’s look at the following scenario by applying the Binary Search algorithm in order for you to understand how Binary Search works.

The Guessing Game

Pick a number from 0 – 100 and depending on your guess, I’ll either say Correct, Higher, or Lower. What would you choose?

0 1 49 50 51 99 100

Well, 50 of course! Why? Best case you get it correct. Worst case you’ll either get a “Higher” or “Lower”. Now think about the following, if you got “Higher” you eliminated 0-49, or 51-100 if “Lower”, in other words, you eliminate HALF the possibilities.

50 51 74 75 76 99 100

Well, let’s say it was “Higher”. What would you guess after? 75. Since it’s in between 50 – 100. If you didn’t guess correctly, you’ll be facing the similar scenario as before. You’ll end up eliminating half the possibilities!

Binary Search Algorithm

The following is the recursive implementation.

int binarysearch(vector  vec, int low, int high, int key)
{
    //Not found
    if ( low > high )
    {
          return -1;
    }

    //Finding the middle index between high and low
    int mid = (low + high)/2;

    //Returning the index if key is found
    if ( vec[mid] == key )
    {
          return mid;
    }
    //If middle index value is larger than our key, we search the lower half of the vector
    //else we search the upper half of the vector
    else if ( vec[mid] > key )
    {
          return binarysearch(vec, low, mid-1, key);
    }
    else
    {
          return binarysearch(vec, mid+1, high, key);
    }
}

Example of Binary Search

Let’s say our container held the values 0-100 in its respective index values. Let’s say the value we are looking for is 57.

First iteration

Index: 0 1 49 50 51 99 100
Value 0 1 49 50 51 99 100
Parameters: low mid high

50 < 57, so search through the upper half of our vector.

Second iteration

Index: 51 52 74 75 76 99 100
Value 51 52 74 75 76 99 100
Parameters: low mid high

75 > 57, so search through the lower half of our vector.

Third iteration

Index: 51 52 62 63 64 73 74
Value 51 52 62 63 64 73 74
Parameters: low mid high

63 > 57, so search through the lower half of our vector.

Fourth iteration

Index: 51 52 56 57 58 61 62
Value 51 52 56 57 58 61 62
Parameters: low mid high

57 == 57!

Tags: , , , , , , , ,

  • Baks

    Can you please provide an example of binary search using a for loop.

  • Baks

    Can you please provide an example of binary search using a for loop.

  • Baks

    Can you please provide an example of binary search using a for loop.