Is this linear search implementation actually useful?

Posted by Helper Method on Stack Overflow See other posts from Stack Overflow or by Helper Method
Published on 2010-03-22T21:47:43Z Indexed on 2010/03/22 21:51 UTC
Read the original article Hit count: 221

Filed under:

In Matters Computational I found this interesting linear search implementation (it's actually my Java implementation ;-)):

public static int linearSearch(int[] a, int key) {
    int high = a.length - 1;
    int tmp  = a[high];

    // put a sentinel at the end of the array   
    a[high] = key;

    int i = 0;

    while (a[i] != key) {
        i++;
    }

    // restore original value
    a[high] = tmp;

    if (i == high && key != tmp) {
        return NOT_CONTAINED;
    }

    return i;
}

It basically uses a sentinel, which is the searched for value, so that you always find the value and don't have to check for array boundaries. The last element is stored in a temp variable, and then the sentinel is placed at the last position. When the value is found (remember, it is always found due to the sentinel), the original element is restored and the index is checked if it represents the last index and is unequal to the searched for value. If that's the case, -1 (NOT_CONTAINED) is returned, otherwise the index.

While I found this implementation really clever, I wonder if it is actually useful. For small arrays, it seems to be always slower, and for large arrays it only seems to be faster when the value is not found. Any ideas?

© Stack Overflow or respective owner

Related posts about algorithm