Quickly find whether a value is present in a C array?

前端 未结 15 1221
灰色年华
灰色年华 2021-01-29 17:30

I have an embedded application with a time-critical ISR that needs to iterate through an array of size 256 (preferably 1024, but 256 is the minimum) and check if a value matches

15条回答
  •  有刺的猬
    2021-01-29 18:03

    This is more like an addendum than an answer.

    I've had a similar case in the past, but my array was constant over a considerable number of searches.

    In half of them, the searched value was NOT present in array. Then I realized I could apply a "filter" before doing any search.

    This "filter" is just a simple integer number, calculated ONCE and used in each search.

    It's in Java, but it's pretty simple:

    binaryfilter = 0;
    for (int i = 0; i < array.length; i++)
    {
        // just apply "Binary OR Operator" over values.
        binaryfilter = binaryfilter | array[i];
    }
    

    So, before do a binary search, I check binaryfilter:

    // Check binaryfilter vs value with a "Binary AND Operator"
    if ((binaryfilter & valuetosearch) != valuetosearch)
    {
        // valuetosearch is not in the array!
        return false;
    }
    else
    {
        // valuetosearch MAYBE in the array, so let's check it out
        // ... do binary search stuff ...
    
    }
    

    You can use a 'better' hash algorithm, but this can be very fast, specially for large numbers. May be this could save you even more cycles.

提交回复
热议问题