Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ Beginner Algorithms
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 27-Apr-10 6:10am
7mesho428
Edited 27-Apr-10 9:56am
Moak11.4K
v3
Rate this: bad
good
Please Sign up or sign in to vote.

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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: Thumbs Down | :thumbsdown: and also: Dead | X|
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Thanks you Mr. Richard! Smile | :) ........
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,107
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,382


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 27 Apr 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100