In Computing Questions, I found an interesting linear search implementation (this is actually my Java implementation ;-)):
public static int linearSearch(int[] a, int key) {
int high = a.length - 1;
int tmp = a[high];
a[high] = key;
int i = 0;
while (a[i] != key) {
i++;
}
a[high] = tmp;
if (i == high && key != tmp) {
return NOT_CONTAINED;
}
return i;
}
Basically, it uses a sentinel signal, which is the sought value, so you always find the value and should not check the boundaries of the array. The last element is stored in the temp variable, and then the controller is placed at the last position. When a value is found (remember, it is always found because of the sentinel), the original element is restored, and the index is checked if it represents the last index and does not match the found value. If this case, -1 (NOT_CONTAINED) is returned, otherwise an index.
, , , . , , , , . ?
++, .