How fast can you make linear search?

前端 未结 20 1861
死守一世寂寞
死守一世寂寞 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:09

    In one of the comments you said the array length is 64.

    Well if you must do it linearly, you can do:

    int i = -1;
    do {
      if (arr[0] >= key){i = 0; break;}
      if (arr[1] >= key){i = 1; break;}
      ...
      if (arr[62] >= key){i = 62; break;}
      if (arr[63] >= key){i = 63; break;}
    } while(0);
    

    However, I seriously doubt if that is faster than this binary search: *

    int i = 0;
    if (key >= arr[i+32]) i += 32;
    if (key >= arr[i+16]) i += 16;
    if (key >= arr[i+ 8]) i +=  8;
    if (key >= arr[i+ 4]) i +=  4;
    if (key >= arr[i+ 2]) i +=  2;
    if (key >= arr[i+ 1]) i +=  1;
    

    *Thanks to Jon Bentley for that one.

    Added: since you said this table is prepared once for a large number of searches, and you want fast, you could allocate some space somewhere and generate machine code with the values hard-wired into it. It could either be linear or binary search. If binary, the machine code would look like what the compiler would generate from this:

    if (key < value32){
      if (key < value16){
        ...
      }
      else {
        ...
      }
    }
    else {
      if (key < value48){
        ...
      }
      else {
        ...
      }
    }
    

    Then you just copy that into a place where you can call it.

    OR you could print the code above, compile and link it on the fly into a dll, and load the dll.

提交回复
热议问题