I\'m looking to optimize this linear search:
static int
linear (const int *arr, int n, int key)
{
int i = 0;
while (i < n) {
Since you can put known values after the last valid entry, add an extra element n+1 = max to make sure the loop doesn't go past the end of the array without having to test for i < n.
static int
linear (const int *arr, int n, int key)
{
assert(arr[n] >= key);
int i = 0;
while (arr[i] < key) {
++i;
}
return i;
}
You could also try unrolling the loop, with the same sentinel value:
static int
linear (const int *arr, int n, int key)
{
assert(arr[n] >= key);
int i = 0;
while (true) {
if (arr [i++] >= key)
break;
if (arr [i++] >= key)
break;
if (arr [i++] >= key)
break;
if (arr [i++] >= key)
break;
}
return --i;
}