Binary Search implementation in C++



#include<iostream>


using namespace std;

int binarySearch(int [], int find, int left, int right);

main()
{
      int arr[] = {-5, -2, 1, 3, 4, 6, 8, 9, 11};
      int search;
      
      for(int i=0; i< sizeof(arr)/sizeof(int); i++)
      {
              cout<<arr[i]<<" ";
      }
      
                
      cout<<"\n\nEnter a number to search: ";
      cin>>search;
      
      if(binarySearch(arr, search, 0, sizeof(arr)/sizeof(int)-1) != -999 ){
                           
          cout<<"Found(index): "<<binarySearch(arr, search, 0, sizeof(arr)/sizeof(int)-1)<<endl;
      }
      else
      {
          cout<<"Sorry! I cannot find that element"<< endl;
      }
          
      
system("pause");
}

int binarySearch(int arr[], int find, int left, int right)
{
     int mid = (left + right )/2; //
     
     if(left == 0 && right ==0) //bug fix--if searching number is located in the first index
             mid = 0;
             
     if(find == arr[mid])
     {
            return mid;
     } 
     else if(find < arr[mid])
     {
           return binarySearch(arr, find, left, mid - 1);
     }
     else if(find > arr[mid])
     {
          return binarySearch(arr, find, mid + 1 , right);
     }
     else
     {
         return -999;
     }
}


Advertisements

About praveenaj

I'm just an average guy who enjoys doing Programming/Web Designs/Pencil art & drinking coffee :)
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s