Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing a search algorithm in C

Can the performance of this sequential search algorithm (taken from The Practice of Programming) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?

int lookup(char *word, char*array[])
{
    int i

    for (i = 0; array[i] != NULL; i++)
        if (strcmp(word, array[i]) == 0)
            return i;

    return -1;
}
like image 701
David Avatar asked Aug 19 '08 07:08

David


People also ask

How can a search algorithm improve further?

The goal is that if the same element is searched again then the operation must take lesser time. Therefore, in such a case, Linear Search can be improved by using the following two methods: Transposition. Move to Front.

What is optimization in C?

Optimization is a program transformation technique, which tries to improve the code by making it consume less resources (i.e. CPU, Memory) and deliver high speed. In optimization, high-level general programming constructs are replaced by very efficient low-level programming codes.

How will you optimize a binary search solution?

The above function is the function G. Also note that on increasing 'f', the number of differences ≤ f will also increase thus the function G is a monotonic increasing function. Thus we can easily apply binary search to find optimal 'f' such that if count is ≤ k, then increase 'f' else decrease 'f'.


2 Answers

Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for example keeping the list sorted and doing a binary search).

In general optimizing a given algorithm only gets you so far. Choosing a better algorithm (even if it's not completely optimized) can give you a considerable (order of magnitude) performance improvement.

like image 59
Grey Panther Avatar answered Oct 06 '22 09:10

Grey Panther


I think, it will not make much of a difference. The compiler will already optimize it in that direction.

Besides, the variable i does not have much impact, word stays constant throughout the function and the rest is too large to fit in any register. It is only a matter how large the cache is and if the whole array might fit in there.

String comparisons are rather expensive computationally.

Can you perhaps use some kind of hashing for the array before searching?

like image 24
HS. Avatar answered Oct 06 '22 09:10

HS.