2

This is a piece of Wikipedia's sample implementation of interpolation search:

public int interpolationSearch(int[] sortedArray, int toFind){
    // Returns index of toFind in sortedArray, or -1 if not found
    int low = 0;
    int high = sortedArray.length - 1;
    int mid;    
    while (sortedArray[low] <= toFind && sortedArray[high] >= toFind) {
        mid = low +
            ((toFind - sortedArray[low]) * (high - low)) /
            (sortedArray[high] - sortedArray[low]);  //out of range is possible here

        if (sortedArray[mid] < toFind)
            low = mid + 1;
        else if (sortedArray[mid] > toFind)
            // Repetition of the comparison code is forced by syntax limitations.
            high = mid - 1;
        else
            return mid;
    }

    if (sortedArray[low] == toFind)
        return low;
    else
        return -1; // Not found
}

Why is out of range possible there?

EDIT: added the whole code

xemlmrx
  • 65
  • 6
  • I'd say a DivideByZero is possible. Maybe that was meant. You should post the complete code, so that readers can see the `int[] sortedArray` – H H Mar 22 '15 at 22:29
  • Just posted the whole code. How come division by zero can be "fixed" by adding or subtracting 1? – xemlmrx Mar 22 '15 at 22:41
  • Who says it can be fixed that way (for all cases)? – H H Mar 22 '15 at 22:55

1 Answers1

2

Out of range is possible here if an integer overflow occurs. To overcome this you can you float/double rather then a 32 bit integer.

Have a look at this, What's wrong with this Interpolation search implementation?

Community
  • 1
  • 1
Humza
  • 358
  • 1
  • 15