Interpolation search

Perl, Itai, Avni CACM 21:7(1978), 550-553.

EXAMPLE: To look up cat in a dictionary, you expect to find cat near the beginning.

INTERPOLATON SEARCH
  i := 1
  j := n
  LO := ai
  HI := aj
  if x < LO then  return 0
  if x ≥ HI then i := j
                loop invariant:  x ≥ LO and x ≤ HI
  while (i<j) do
        m := floor( i + (j-i)*(x-LO) / (HI-LO) )
        MID := am
        if (x > MID) then
              i := m+1
              LO := MID
        else if (x < MID) then
              j := m-1
              HI := MID
        else
              return MID
  if (x ≠ ai) then i := 0
  return i
The algorithm can be modified to use only one element comparison per loop iteration,
but care must be taken to avoid an infinite loop.
INTERPOLATON SEARCH
  i := 1
  j := n
  LO := ai
  HI := aj
  if x < LO then  return 0
  if x ≥ HI then i := j
                loop invariant:  x ≥ LO and x < HI
  while (i<j) do
        m := floor( i + (j-i)*(x-LO) / (HI-LO) )
                loop invariant:  m ≥ i and m <: j
        MID := am+1
        if (x < MID) then
              j := m
              HI := MID
        else
              i := m+1
              LO := MID
  if (x ≠ ai) then i := 0
  return i

Worst case complexity

O(n)

EXAMPLE: 1,2,3,4,5,...,999,1000,109
        Look for 1000

Average case complexity

O(lg lg n)

Dan Hirschberg
Last modified: Jul 2, 2013