Reputation: 23
I am trying to create a binary search algorithm and have used two sets of if statements for when the sample is even/uneven. The uneven side currently works as planned and returns true, the even side returns true but then goes to the "catch all" piece of code at the bottom of the function and returns false:
bool search(int value, int values[], int n)
{
//searching algorithm
if (n <= 0)
{
return false;
}
//searching algorithm where n is even, if b is not the searched for value, split the sample and run recursively until value is equal to b or n<=0
if (n % 2 == 0)
{
int starte = n / 2;
eprintf("starte is %i", starte);
int startpluse = starte + 1;
int b = values[starte];
eprintf("b is %i", b);
//for (int i=0; i<n; i++){
//printf("%i,",values[i]);}
if (b == value)
{
printf("true\n");
return true;
}
else
{
if (value > b)
{
int o = starte - 1;
int searcharrayc[o];
for (int h = startpluse, l = 0; l < o; h++, l++)
{
searcharrayc[l] = values[h];
}
search(value, searcharrayc, o);
}
if (value < b)
{
int searcharrayd[starte];
for (int m = 0; m < starte; m++)
{
searcharrayd[m] = values[m];
}
search(value, searcharrayd, starte);
}
}
}
//searching algorithm where n is uneven, if a is not the searched for value, split the sample and run recursively until a is equal to the value or n<=0
if (n % 2 == 1)
{
eprintf("n is %i", n);
int start = (n / 2) - 0.5;
int startplus = start + 1;
int a = values[start];
eprintf("a is %i", a);
if (a == value)
{
return true;
}
else
{
if (value > a)
{
int searcharray[start];
for (int i = startplus, j = 0; j < start; i++, j++)
{
searcharray[j] = values[i];
eprintf("i is %i", i);
}
search(value, searcharray, start);
}
if (value < a)
{
int searcharrayb[start];
for (int k = 0; k < start; k++)
{
searcharrayb[k] = values[k];
eprintf("k is %i", k);
}
search(value, searcharrayb, start);
}
}
}
return false;
}
Upvotes: 2
Views: 305
Reputation: 31409
Your code looks like this:
search(...)
{
if(cond)
return false
if(cond)
return true
else
search(...)
return false
}
You need to change it to:
search(...)
{
if(cond)
return false
if(cond)
return true
else
return search(...)
}
Note the extra return before the recursive call to search
Upvotes: 2