12,073,325 members (67,735 online)
Rate this:
See more:
Why my code for recursive binary search not working? The search always return element is not found.

For example: If there are 5 elements - 4, 8, 13, 17, and 21. Search for 17 return no element found.

```#include<iostream>
using namespace std;
int midind, elements, first=0 , last=(elements-1);
int array1[5];
bool searches (int index , int search)
{
if (index>=elements|| index<=0)
{
return false;
}
else if (search==array1[index])
{
cout<<"The number "<<search<<" was found and its index is "<<index<<" \n";
return true;
}
else if (search>array1[index])
{

first= index;
index= static_cast<int>((first+last)*0.5);
return searches (index, search);

}
else if (search<array1[index])
{
last = index;
index = static_cast<int>((first+last)*0.5);
return searches (index , search);
}

}
void main ()
{
int i, search;
cout<<"Enter the number of elements of your integer array  \n";
cin>>elements;
cout<<"Enter the "<<elements<<" elements of your integer array in ascending order \n";
for (i=0 ; i<elements ; i++)
{
cin>>array1[i];
}
for (i=0 ; i<elements ; i++)
{
cout<<array1[i];
cout<<"\t";
}
cout<<endl<<endl;
cout<<"Enter a number to search for: \n";
cin>>search;
midind= static_cast<int>((first+last)*0.5);
searches (midind , search);
}```
Posted 27-Apr-10 6:10am
7mesho428
Edited 27-Apr-10 9:56am
Moak11.5K
v3

Rate this:

## Solution 1

7mesho wrote:
int midind, elements, first=0 , last=(elements-1);

The above statement makes no sense, and should give a compiler warning. You cannot set `last` from `elements` before `elements` contains any value.
Rate this:

## Solution 2

Your basic problem seems to be the first condition:

`if (index>=elements|| index<=0)`

In the first run index will always be <= 0 (you set it to 0 yourself)

Change the condition to:

`if (index>=elements|| index<0)`

EDIT: But Richard's point is also valid and to whoever downvoted him I say: and also:
v2
Rate this:

## Solution 4

Thanks you Mr. Richard! ........

Top Experts
Last 24hrsThis month
 OriginalGriff 510 Dave Kreskowiak 475 CPallini 335 F-ES Sitecore 210 CHill60 200
 Dave Kreskowiak 2,511 OriginalGriff 2,164 Richard MacCutchan 1,675 CPallini 1,387 CHill60 1,219