16. Data Structure - Interpolation Search
16. Data Structure - Interpolation Search
Interpolation Search
Interpolation search is an improved variant of binary search. This search
algorithm works on the probing position of the required value. For this
algorithm to work properly, the data collection should be in a sorted form and
equally distributed.
Binary search has a huge advantage of time complexity over linear search.
Linear search has worst-case complexity of Ο(n) whereas binary search has
Ο(log n).
There are cases where the location of target data may be known in advance.
For example, in case of a telephone directory, if we want to search the
telephone number of Morphius. Here, linear search and even binary search will
seem slow as we can directly jump to memory space where the names start
from 'M' are stored.
Let's assume that the elements of the array are linearly distributed.
General equation of line : y = m*x + c.
y is the value in the array and x is its index.
Now putting value of lo,hi and x in the equation
arr[hi] = m*hi+c ----(1)
arr[lo] = m*lo+c ----(2)
x = m*pos + c ----(3)
m = (arr[hi] - arr[lo] )/ (hi - lo)
subtracting eqxn (2) from (3)
x - arr[lo] = m * (pos - lo)
lo + (x - arr[lo])/m = pos
pos = lo + (x - arr[lo]) *(hi - lo)/(arr[hi] - arr[lo])
Another way : Algorithm
# interpolation search
# with recursion
(x - arr[lo]))
if arr[pos] == x:
return pos
Output