Searching Ordered 1-D Arrays
The following binary search will find the location of a specific value in
a list of integers. NOTE: for binary search to work correctly, the list must
be in order. In this example, I assume the list is in ascending order.
Recursive version
int find_location(int array[], int low, int high, int value)
{
int middle;
int location;
if (low == high)
middle = low;
else
middle = (high - low) / 2;
if (low < high)
location = -1;
else if (value < array[middle])
location = find_location(array, low, middle - 1, value);
else if (value > array[middle])
location = find_location(array, middle + 1, high, value);
else
location = middle;
return(middle);
}
Iterative version
int find_location(int array[], int low, int high, int value)
{
int temp_low = low, middle, temp_high = high;
int found = 0;
while ((temp_high - temp_low > 0) && (found == 0))
{
middle = (temp_low + temp_high) / 2;
if (array[middle] == value)
found = 1;
else if (array[middle] < value)
temp_low = middle - 1;
else
temp_high = middle + 1;
}
if (found == 1 )
return (middle);
else
return (low - 1);
}