#include <stdio.h>
#include <stdlib.h>
int BinarySearch(int *, int, int, int);
int main( ) {
// initialize our array of numbers
srand(0);
int a, num, ans, SIZE;
printf("Enter the size of our array : ");
scanf("%d", &SIZE);
int *array = malloc( sizeof(int) * SIZE );
num = 0;
for (a = 0; a < SIZE; a++) {
num = num + rand()%2 + 1;
printf("%d ", num);
array[a] = num;
}
printf("\n\n");
printf("Enter a number to find : ");
scanf("%d", &num);
ans = BinarySearch(array, num, 0, SIZE-1);
if (ans != -1)
printf("Found %d at location %d\n", num, ans);
else
printf("Count not find %d in the array\n", num);
return 0;
}
int BinarySearch(int *array, int num, int first, int last) {
printf("In binary search with range %d and %d\n", array[first], array[last]);
// base case #1 - count not find, return -1
if (first > last) return -1;
// base case #2 - found it at the "mid" locatin, return that location
int mid = (first + last) / 2;
if (array[mid] == num)
return mid;
// two recursive cases - call BinarySearch with either lower half or upper half
else if (array[mid] < num)
return BinarySearch(array, num, mid+1, last);
else
return BinarySearch(array, num, first, mid-1);
}