Binary search an array - C++ Data Structure

C++ examples for Data Structure:Search

Description

Binary search an array

Demo Code

#include <iostream>
using namespace std;
int binarySearch(int [], int, int);  // function prototype
int main()//w w w  . ja  va 2 s  .c om
{
   const int NUMEL = 10;
   int nums[NUMEL] = {5,10,22,32,4,7,73,8,9,11};
   int item, location;
   cout << "Enter the item you are searching for: ";
   cin  >> item;
   location = binarySearch(nums, NUMEL, item);
   if (location > -1)
      cout << "The item was found at index location " << location << endl;
   else
      cout << "The item was not found in the array\n";
   return 0;
}
int binarySearch(int list[], int size, int key)
{
      int left, right, midpt;
      left = 0;
      right = size -1;
      while (left <= right)
      {
         midpt = (int) ((left + right) / 2);
         if (key == list[midpt])
         {
            return midpt;
         }
         else if (key > list[midpt])
            left = midpt + 1;
         else
            right = midpt - 1;
      }
      return -1;
}

Result


Related Tutorials