13,004,094 members (112,270 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 5:10am
7mesho428
Updated 27-Apr-10 8:56am
Moak11.6K
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:

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

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

Change the condition to:

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

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

## Solution 4

Thanks you Mr. Richard! :)........

Top Experts
Last 24hrsThis month
 RickZeeland 244 Richard MacCutchan 135 F-ES Sitecore 125 OriginalGriff 123 Dave Kreskowiak 115
 OriginalGriff 5,030 ppolymorphe 2,567 RickZeeland 2,495 Kornfeld Eliyahu Peter 2,126 Richard Deeming 1,693