Here is a cleaned up version of the original example:
Code:
#include<stdio.h>
#include<stdlib.h>
int * binarySearchRecursive(int value, int *first, int *last) {
int middle;
if(first <= last) {
middle = (last - first) / 2;
// (note, if first == last, then middle == 0)
if (*(first + middle) == value) // if match found return it
return (first + middle);
if (*(first + middle) > value) // if greater search left half
return binarySearchRecursive(value, first, first + middle - 1);
// else search right half
return binarySearchRecursive(value, first + middle + 1, last);
}
else // if first > last, element not found
return NULL;
}
int main() {
int list[20] = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
55, 60, 65, 70, 75, 80, 85, 90, 95, 100};
int *ptr, value = 85;
ptr = binarySearchRecursive(value, &list[0], &list[19]);
if (ptr != NULL) {
printf("The value %d is at address %p in the sorted array.\n", value, ptr);
printf("Test: list[%d] = %d\n\n", (ptr-list), *ptr);
}
else {
printf("%d was not found in the list.\n\n", value);
}
return(0);
}