binary search

I have gone through the program many times and still unable to detect my fallacy. Kindly point out?
The problem is such that i can't get the right output for certain inputs and I can for others.

#include<iostream>
using namespace std;

int binarysearch();
int array[] = {1,2,3,4,5,6,7,8,9,10,11};
int age;
int result;
int main()
{
cout<< "enter the age you wish to search for"<< endl;
cin >> age;
result= binarysearch();
if (result== -1)
{
cout << "age no exist in the list" << endl;
}
else
{
cout<< "age given at element no. "<< result << endl;
}
}
int binarysearch()
{
int first= 0, last= 10;
int middle;
bool found = false;

while( !found && first <= last)
{
middle= (first + last)/2;
if (array[middle] ==age)
{found= true;
result= middle +1; }
else if(array[middle] >> age)
{
last= middle- 1;}
else
{
first= middle+1;}
}
return result;
}
Last edited on
Okay, if I put if (array[middle] > age) instead of >>, then it is working.

Im a little confused. We're intending to compare the two and what exactly does the >> operator do here within the if statement?
The operator>> is the bitshift right operator, inherited from C.
However in C++ it is overloaded for input streams.

X >> Y

bitwise shift X right by Y bits

if X has representation 00001111 and Y is 2, then:

00001111 >> 2 == 00000011

00001111 is the number 15
00000011 is the number 3


http://ideone.com/PzSAs2
Yes, I just read it up! Thanks again, mate!
Topic archived. No new replies allowed.