Searching 1-D Arrays
Find the smallest value in an array
int find_small(int array[], int low, int high)
{
int small, index;
small = array[low];
for (index = low + 1; index <= high; index++)
{
if (array[index] < small)
small = array[index];
}
return small;
}
Find the location of a specified value in an array
int find_value_location(int array[], int low, int high, int value)
{
int location, found, index;
location = low - 1;
found = 0; /*0 stands for false in C*/
index = low;
while ((index <= high) && (found == 0))
{
if (array[index] == value)
{
location = index;
found = 1;
}
index = index + 1;
}
return location;
}
Recursive Binary Search to find the location of a specified value
/* binary search of an array to find a location. Array must be in ascending
order.
C has a function in stdlib.h called bsearch which is a generic binary
search on a 1-d array. To use bsearch() you have to pass a function as
a parameter to the subprogram. This is also true of qsort(), which is
a C quicksort subprogram.
*/
int binary_search(int array[], int low, int high, int value)
{
int middle = (high - low)/2;
int location;
if (low == high)
middle = low;
else
middle = (high - low)/2;
if (low > high)
location = -1;
else if (value < array[middle])
location = binary_search(array, low, middle - 1, value);
else if (value > array[middle])
location = binary_search(array, middle + 1, high, value);
else
location = middle;
return(location);
}
main() function to test the above searches
int main(void)
{
int arr1[10] = {3, 5, 2, 9, 3, 6, 4};
int arr2[10] = {1, 3, 4, 5, 6, 7, 8};
int small, location;
small = find_small(arr1, 0, 6);
printf("\nSmall = %d", small);
location = find_value_location(arr1, 0, 6, small);
printf("\nlocation = %d", location);
location = binary_search(arr2, 0, 6, 4);
printf("\nlocation = %d", location);
return (0);
}