Is this linear search implementation useful?

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];

    // 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;
}

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.

, , , . , , , , . ?

++, .

+1
6

, , a[high] a[high] key, key tmp, , a[high] . a[high] , , key.

java, JVM , while , .

+10

?

?

, concurrency?

- .

+7

. "" - , . 0 ( ).

. - 1960- .

+5

. , ( " ? ?" ) .

, , , , . (, OP) , .

, , , , .

- .

: ?

+2

See also Finding a Tiger in Africa. Punchline = An experienced programmer places a tiger in Cairo so that the search ends.

+2
source

Yes - this is because the while loop does not have 2 comparisons, not a standard search.

It is twice as fast. It is defined as an optimization in Knuth Vol 3.

0
source

Source: https://habr.com/ru/post/1748847/


All Articles