How fast can you make linear search?

前端 未结 20 1879
死守一世寂寞
死守一世寂寞 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条回答
  •  Happy的楠姐
    2020-12-23 22:02

    You could avoid n checks similar to how loop unrolling does it

    static int linear(const int *array, int arraySize, int key)
    {
      //assuming the actual size of the array is always 1 less than arraySize
      array[arraySize] = key; 
    
      int i = 0;
      for (; ; ++i)
      {
         if (array[i] == key) return i;
      }
    }
    

提交回复
热议问题