What is the fastest search method for a sorted array?

前端 未结 8 464
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 04:57

Answering to another question, I wrote the program below to compare different search methods in a sorted array. Basically I compared two implementations of Interpolation search

8条回答
  •  后悔当初
    2021-02-01 05:43

    The implementation of the binary search that was used for comparisons can be improved. The key idea is to "normalize" the range initially so that the target is always > a minimum and < than a maximum after the first step. This increases the termination delta size. It also has the effect of special casing targets that are less than the first element of the sorted array or greater than the last element of the sorted array. Expect approximately a 15% improvement in search time. Here is what the code might look like in C++.

    int binarySearch(int * &array, int target, int min, int max)
    { // binarySearch
      // normalize min and max so that we know the target is > min and < max
      if (target <= array[min]) // if min not normalized
      { // target <= array[min]
          if (target == array[min]) return min;
          return -1;
      } // end target <= array[min]
      // min is now normalized
    
      if (target >= array[max]) // if max not normalized
      { // target >= array[max]
          if (target == array[max]) return max;
          return -1;
      } // end target >= array[max]
        // max is now normalized
    
      while (min + 1 < max)
      { // delta >=2
        int tempi = min + ((max - min) >> 1); // point to index approximately in the middle between min and max
        int atempi = array[tempi]; // just in case the compiler does not optimize this
        if (atempi > target)max = tempi; // if the target is smaller, we can decrease max and it is still normalized        
        else if (atempi < target)min = tempi; // the target is bigger, so we can increase min and it is still normalized        
            else return tempi; // if we found the target, return with the index
            // Note that it is important that this test for equality is last because it rarely occurs.
      } // end delta >=2
      return -1; // nothing in between normalized min and max
    } // end binarySearch
    

提交回复
热议问题