Reputation: 275
Have this search function that works when I compile in Linux using clang, but on Windows using MinGW gcc, I do not get the right answer. Included in the code is an array where clearly the value I'm looking for is in the array. So output should be "Found it!". Anyone know what might the issue be with windows?
#include <stdio.h>
#include <stdbool.h>
bool re_search(int value, int values[], int first, int last);
int main(void)
{
int value = 12;
int values[] = {2,4,5,12,23,34};
int n = 6;
if (re_search(value, values, 0, n-1))
{
printf("Found it!\n");
}
else
{
printf("Did not find it\n");
}
return 0;
}
bool re_search(int value, int values[], int first, int last)
{
last = last-1;
int middle = (first+last)/2;
while (first <= last)
{
if (value == values[middle])
{
return true;
}
else if (value > values[middle])
{
first = middle + 1;
middle = (first + last) / 2;
return re_search(value, &values[middle], first, last);
}
else
{
last = middle - 1;
middle = (first + last) / 2;
return re_search(value, &values[first], first, last);
}
}
return false;
}
Upvotes: 1
Views: 147
Reputation: 40145
does not matter whether GCC and windows.
bool re_search(int value, int values[], int first, int last){
if (first <= last){
int middle = (first+last)/2;
if (value == values[middle]){
return true;
} else if (value > values[middle]){
return re_search(value, values, middle + 1, last);
} else {
return re_search(value, values, first, middle - 1);
}
}
return false;
}
bool re_search(int value, int values[], int first, int last){
while (first <= last){
int middle = (first+last)/2;
if (value == values[middle]){
return true;
} else if (value > values[middle]){
first = middle + 1;
} else {
last = middle - 1;
}
}
return false;
}
Upvotes: 1
Reputation: 46667
Your recursive call return re_search(value, &values[middle], first, last);
is passing in both an array which starts at the midpoint, and a new value of first
which counts from the whole array's start. You want to do one or the other; not both.
That is, you first call with:
values == {2,4,5,12,23,34}
first == 0
last == 5
In the first iteration, you try middle == 2
, so values[middle]
is 5, which is less than 12. You then recurse with
values == {12,23,34}
first == 3
last == 5
And - oh dear! - even values[first]
is now out of range. Chances are, on Linux you got (un)lucky and hit the value you were searching for past the end of the array.
Upvotes: 3