In this function:
1 2 3 4 5 6 7 8 9 10
|
int FindLinear(int array[], int value, int key)
{
for (int i=0; i<value; i++)
{
if (array[i]==key)
return i;
}
return -1
}
|
value
is really the size of the array.
key
is the value to search for.
The for loop checks each element in the array to see whether it matches the key. If a match is found, the value of
i
is returned immediately, without any need to continue with the rest of the loop.
Since the array size is given by
value
, a successful search will result in a value of
i
in the range 0 to value-1. For example, if the array size is 10, a valid result would be in the range 0 to 9.
In order to indicate that the search has failed, when the for loop reaches the end without finding the key, the value -1 is returned. This is convenient, because any valid result must be a positive number, so a negative number is used to show that it has failed. The particular value -1 is a good idea as it shows clearly a specific meaning.