#include <stdio.h>
#include <stdlib.h>
/* Puzzle D25 -- find the element in an
| array closest to a particular value
|
| Return the index of the closest element
|
*/
int linearSearchClosest( int size, int arr[], int target )
{
int j;
/* Closest difference, so far, and index of that elemetn */
int closeDiff, closeInx;
int diff;
/* Closest element so far is element zero */
closeDiff = arr[0] - target;
if ( closeDiff < 0 ) closeDiff = -closeDiff;
closeInx = 0;
/* Search for a smaller difference amoung the remaining elts */
for ( j=1; j < size; j++ )
{
/* Difference between the target and element j */
diff = arr[j] - target;
if ( diff < 0 ) diff = -diff;
if ( diff < closeDiff )
{
closeDiff = diff;
closeInx = j;
}
}
return closeInx;
}
void printArray( int size, int arr[] )
{
const int N = 10;
int j;
for ( j=0; j < size; j++ )
{
if ( j%N == N-1 )
printf("%4d\n", arr[j] );
else
printf("%4d ", arr[j] );
}
}
int main()
{
const int SIZE = 10;
int x[] = { -5, -3, 0, 6, 4, 16, -3, 0, 7, 9 };
int loc, target;
char input[32];
printArray( SIZE, x );
printf("target:");
scanf("%s", input );
while ( strcmp( input, "q" ) != 0 )
{
target = atoi( input );
loc = linearSearchClosest( SIZE, x, target );
printf("Closest element to %d found at index %d\n", target, loc );
printf("target:");
scanf("%s", input );
}
return 0;
}
Comments: The user interaction in the testing program could
be improved. As it is, if the user enters a non-numeric string other than exactly
"q", the program continues, the function atoi() returns
a zero, and zero is used as a target.
Try to improve the testing program, if you want.