Click here to Skip to main content
15,879,047 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
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)
	{
		cout<<"The number "<<search<<" was not found!! \n";
		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];
	}
	cout<<endl<<"Your integer array is:"<<endl;
	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
Updated 27-Apr-10 8:56am
v3

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.
 
Share this answer
 
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: :thumbsdown: and also: X|
 
Share this answer
 
v2
Thanks you Mr. Richard! :)........
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900