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

前端 未结 15 1269
灰色年华
灰色年华 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 17:49

    Use a hash set. It will give O(1) lookup time.

    The following code assumes that you can reserve value 0 as an 'empty' value, i.e. not occurring in actual data. The solution can be expanded for a situation where this is not the case.

    #define HASH(x) (((x >> 16) ^ x) & 1023)
    #define HASH_LEN 1024
    uint32_t my_hash[HASH_LEN];
    
    int lookup(uint32_t value)
    {
        int i = HASH(value);
        while (my_hash[i] != 0 && my_hash[i] != value) i = (i + 1) % HASH_LEN;
        return i;
    }
    
    void store(uint32_t value)
    {
        int i = lookup(value);
        if (my_hash[i] == 0)
           my_hash[i] = value;
    }
    
    bool contains(uint32_t value)
    {
        return (my_hash[lookup(value)] == value);
    }
    

    In this example implementation, the lookup time will typically be very low, but at the worst case can be up to the number of entries stored. For a realtime application, you can consider also an implementation using binary trees, which will have a more predictable lookup time.

提交回复
热议问题