There are multiple issues in your code:
Defining midpoint() as a macro is error prone. Your definition is not properly parenthesized, it should read:
#define midpoint(start, end) (((start) + (end)) / 2)
Written as half the sum, it actually would invoke undefined behavior for large values of start and end, a much safer version would be start + (end - start) / 2, but should not be used in a macro as it evaluates start twice. Just write the code in the function directly.
Your initialization function iterates one step too far, the loop should read:
for (int i = 0, number = 0; i < SIZE; i++) {
array[i] = number;
number += 2;
}
find() should indeed return the index of the value found or -1 if not found. You do not return anything. make it return -1 upon failure and the value of the recursive call when recursing.
the arguments to find are start, the starting index of the range, included in the search, and end the upper bound, excluded from the search. You should not pass mid - 1 when recursing on the left part.
Here is a corrected version:
#include <stdio.h>
#define SIZE 15
void fill_array(int array[], int size) {
// here I just fill array with even numbers
for (int i = 0, number = 0; i < SIZE; i++) {
array[i] = number;
number += 2;
}
}
int find(int target, const int array[], int start, int end) {
if (start >= end) {
// empty range: not found
return -1;
}
int mid = start + (end - start) / 2;
if (target == array[mid]) {
return mid;
}
if (target > array[mid]) {
return find(target, array, mid + 1, end);
} else {
return find(target, array, start, mid);
}
}
void locate(int value, const int array[], int size) {
int res = find(value, array, 0, size);
if (res < 0) {
printf("%d was not found in the array\n", value);
} else {
printf("%d was found at offset %d\n", value, res);
}
}
int main(void) {
int array[SIZE];
fill_array(array, SIZE);
locate(1, array, SIZE);
locate(2, array, SIZE);
return 0;
}
Output:
1 was not found in the array
2 was found at offset 1
Note that find() can be implemented as a loop with less code:
int find(int target, const int array[], int start, int end) {
while (start < end) {
int mid = start + (end - start) / 2;
if (target == array[mid]) {
return mid;
}
if (target > array[mid]) {
start = mid + 1;
} else {
end = mid;
}
}
return -1;
}
find()misses anyreturnstatement.i <= SIZE-->i < SIZE