How fast can you make linear search?

前端 未结 20 1886
死守一世寂寞
死守一世寂寞 2020-12-23 21:46

I\'m looking to optimize this linear search:

static int
linear (const int *arr, int n, int key)
{
        int i = 0;
        while (i < n) {
                      


        
20条回答
  •  借酒劲吻你
    2020-12-23 22:19

    Since you can put known values after the last valid entry, add an extra element n+1 = max to make sure the loop doesn't go past the end of the array without having to test for i < n.

    static int
    linear (const int *arr, int n, int key)
    {
            assert(arr[n] >= key);
            int i = 0;
            while (arr[i] < key) {
                    ++i;
            }
            return i;
    }
    

    You could also try unrolling the loop, with the same sentinel value:

    static int
    linear (const int *arr, int n, int key)
    {
            assert(arr[n] >= key);
            int i = 0;
            while (true) {
                    if (arr [i++] >= key)
                            break;
                    if (arr [i++] >= key)
                            break;
                    if (arr [i++] >= key)
                            break;
                    if (arr [i++] >= key)
                            break;
            }
            return --i;
    }
    

提交回复
热议问题