Interpolation Search
Interpolation search is only applied when the elements in array is sorted and evenly distributed. It is a combination of both binary search and linear search algorithm. Binary Search always goes to middle element to check. On the other hand interpolation search may go to different locations according the value of key being searched.
For example if the value of key is closer to the last element, interpolation search is likely to start search toward the end side.
Algorithm:
Rest of the Interpolation algorithm is same except the above partition logic.
Step1: In a loop, calculate the value of “pos” using the probe position formula.
Step2: If it is a match, return the index of the item, and exit.
Step3: If the item is less than arr[pos], calculate the probe position of the left sub-array. Otherwise calculate the same in the right sub-array.
Step4: Repeat until a match is found or the sub-array reduces to zero.
Listing: Following program is showing the implementation of interpolation search.
// C program to implement interpolation search
#include<stdio.h>
// If x is present in arr[0..n-1], then returns
// index of it, else returns -1.
int interpolationSearch(int arr[], int n, int x)
{
// Find indexes of two corners
int low = 0, high = (n - 1);
// Since array is sorted, an element present
// in array must be in range defined by corner
while (low <= high && x >= arr[low] && x <= arr[high])
{
// Probing the position with keeping
// uniform distribution in mind.
int pos = low + (((double)(high-low) /
(arr[high]-arr[low]))*(x - arr[low]));
// Condition of target found
if (arr[pos] == x)
return pos;
// If x is larger, x is in upper part
if (arr[pos] < x)
low = pos + 1;
// If x is smaller, x is in lower part
else
high = pos - 1;
}
return -1;
}
int main()
{
// Array of items on which search will
// be conducted.
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
24, 33, 35, 42, 47};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 21; // Element to be searched
int index = interpolationSearch(arr, n, x);
// If element was found
if (index != -1)
printf("Element found at index %d", index);
else
printf("Element not found.");
return 0;
}