Open In App

Interpolation search vs Binary search

Last Updated : 11 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. 

Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Search is likely to start search toward the end side.

Interpolation search and binary search are both algorithms for searching for a specific element in a sorted list or array. Both algorithms have an average-case time complexity of O(log n), which means that the time required to perform the search grows logarithmically with the size of the list.

However, there are some key differences between interpolation search and binary search:

Interpolation search estimates the position of the target element based on the values of the elements surrounding it, while binary search always starts by checking the middle element of the list.

Interpolation search is more efficient than binary search when the elements in the list are uniformly distributed, while binary search is more efficient when the elements in the list are not uniformly distributed.

Interpolation search can take longer to implement than binary search, as it requires the use of additional calculations to estimate the position of the target element.

Example : 

C++




#include<bits/stdc++.h>
using namespace std;
 
int interpolation_search(int arr[],int target, int n){
    int low = 0;
    int high = n - 1;
 
    while (low <= high && target >= arr[low] && target <= arr[high]){
        // Calculate the position of the target element based on its value
        int pos = low + (((target - arr[low]) * (high - low)) / (arr[high] - arr[low]));
 
         // Check if the target element is at the calculated position
        if( arr[pos] == target){
            return pos;
        }
 
        // If the target element is less than the element at the calculated position, search the left half of the list
        if(arr[pos] > target){
            high = pos - 1;
        }
        else{
            // If the target element is greater than the element at the calculated position, search the right half of the list
            low = pos + 1;
        }
    }
    return -1;
}
 
int main(){
     
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int n = sizeof(arr)/sizeof(int);
    int target = 5;
    int index = interpolation_search(arr, target, n);
     
    // cout << index << endl;
    if(index == -1){
        cout << target << " not found in the list" << endl;
    }
    else{
        cout << target << " found at index " << index << endl;
    }
}
 
// The code is contributed by Gautam goel.


Java




class GFG {
  public static int interpolationSearch(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
 
        while (low <= high && target >= arr[low] && target <= arr[high]) {
            // Calculate the position of the target element based on its value
            int pos = low + (((target - arr[low]) * (high - low)) / (arr[high] - arr[low]));
 
            // Check if the target element is at the calculated position
            if (arr[pos] == target) {
                return pos;
            }
 
            // If the target element is less than the element at the
            // calculated position, search the left half of the list
            if (arr[pos] > target) {
                high = pos - 1;
            } else {
                // If the target element is greater than the element
                // at the calculated position, search the right half of the list
                low = pos + 1;
            }
        }
        return -1;
    }
   
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int target = 5;
        int index = interpolationSearch(arr, target);
 
        if (index == -1) {
            System.out.println(target + " not found in the list");
        } else {
            System.out.println(target + " found at index " + index);
        }
    }
}
 
//The code is contributed by Rohit Singh.


Python3




def interpolation_search(arr, target):
    low = 0
    high = len(arr) - 1
 
    while low <= high and target >= arr[low] and target <= arr[high]:
        # Calculate the position of the target element based on its value
        pos = low + ((target - arr[low]) * (high - low)) // (arr[high] - arr[low])
 
        # Check if the target element is at the calculated position
        if arr[pos] == target:
            return pos
 
        # If the target element is less than the element at the calculated position, search the left half of the list
        if arr[pos] > target:
            high = pos - 1
        else:
            # If the target element is greater than the element at the calculated position, search the right half of the list
            low = pos + 1
 
    return -1
 
 
def main():
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    target = 5
 
    index = interpolation_search(arr, target)
 
    if index == -1:
        print(f"{target} not found in the list")
    else:
        print(f"{target} found at index {index}")
 
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program
{
    static int InterpolationSearch(int[] arr, int target, int n)
    {
        int low = 0;
        int high = n - 1;
 
        while (low <= high && target >= arr[low] && target <= arr[high])
        {
            // Calculate the position of the target element based on its value
            int pos = low + (((target - arr[low]) * (high - low)) / (arr[high] - arr[low]));
 
            // Check if the target element is at the calculated position
            if (arr[pos] == target)
            {
                return pos;
            }
 
            // If the target element is less than the element at the calculated position, search the left half of the list
            if (arr[pos] > target)
            {
                high = pos - 1;
            }
            else
            {
                // If the target element is greater than the element at the calculated position, search the right half of the list
                low = pos + 1;
            }
        }
        return -1;
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int n = arr.Length;
        int target = 5;
        int index = InterpolationSearch(arr, target, n);
 
        // Console.WriteLine(index);
        if (index == -1)
        {
            Console.WriteLine(target + " not found in the list");
        }
        else
        {
            Console.WriteLine(target + " found at index " + index);
        }
    }
}


Javascript




function interpolation_search(arr, target){
    let low = 0;
    let high = arr.length - 1;
 
    while (low <= high && target >= arr[low] && target <= arr[high]){
         
        // Calculate the position of the target element based on its value
        let pos = low + Math.floor(((target - arr[low]) * (high - low)) / (arr[high] - arr[low]));
         
        // Check if the target element is at the calculated position
        if(arr[pos] == target){
            return pos;
        }
 
        // If the target element is less than the element at the calculated position, search the left half of the list
        if(arr[pos] > target){
            high = pos - 1;
        }
        else{
            // If the target element is greater than the element at the calculated position, search the right half of the list
            low = pos + 1;
        }
    }
    return -1;
}
 
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let target = 5;
 
let index = interpolation_search(arr, target);
 
if (index == -1){
    console.log(target, " not found in the list");
}
else{
    console.log(target, " found at index ", index);
}
 
// The code is written by Nidhi goel.


Output

5 found at index 4

On average the interpolation search makes about log(log(n)) comparisons (if the elements are uniformly distributed), where n is the number of elements to be searched. In the worst case (for instance where the numerical values of the keys increase exponentially) it can make up to O(n) comparisons. 

Time Complexity : O(log(log n)) 

space complexity : O(1)
Interpolation Search Article 
Sources: 
http://en.wikipedia.org/wiki/Interpolation_search 
 



Previous Article
Next Article

Similar Reads

Interpolation Search
Given a sorted array of n uniformly distributed values arr[], write a function to search for a particular element x in the array. Linear Search finds the element in O(n) time, Jump Search takes O(? n) time and Binary Search takes O(log n) time. The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted
15+ min read
Interpolation Search in Python
Interpolation Search is an efficient searching algorithm particularly when dealing with the uniformly distributed sorted arrays. It improves upon binary search by the estimating the location of the target element based on its value and the range of the elements in the array. For example, if the target value is closer to the first element, interpola
4 min read
Newton's Divided Difference Interpolation Formula
Interpolation is an estimation of a value within two known values in a sequence of values. Newton's divided difference interpolation formula is an interpolation technique used when the interval difference is not same for all sequence of values. Suppose f(x0), f(x1), f(x2).........f(xn) be the (n+1) values of the function y=f(x) corresponding to the
11 min read
Program to implement Inverse Interpolation using Lagrange Formula
Given task is to find the value of x for a given y of an unknown function y = f(x) where values of some points (x, y) pairs are given.Let, y = f(x) be an unknown function where x in an independent variable. For different values of x, say [Tex]x_0, x_1, x_2, ..., x_m ( i.e [/Tex][Tex]x_k, k=0, 1, 2, 3...m) [/Tex]values of respective [Tex]y_0, y_1, y
8 min read
Program for Stirling Interpolation Formula
Given n number of floating values x, and their corresponding functional values f(x), estimate the value of the mathematical function for any intermediate value of the independent variable x, i.e., at x = a. Examples: Input : n = 5 x[Tex]_1[/Tex] = 0, x[Tex]_2[/Tex] = 0.5, x[Tex]_3[/Tex] = 1.0, x[Tex]_4[/Tex] = 1.5, x[Tex]_5[/Tex] = 2.0 f(x[Tex]_1[/
13 min read
Newton Forward And Backward Interpolation
Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation. Forward Differences: The differences y1 – y0, y2 – y1, y3 – y2, ......, yn – yn–1 when denoted by dy0, dy1, dy2, ......
15+ min read
Bessel's Interpolation
Interpolation is the technique of estimating the value of a function for any intermediate value of the independent variable, while the process of computing the value of the function outside the given range is called extrapolation. Central differences : The central difference operator d is defined by the relations : Similarly, high order central dif
12 min read
Lagrange's Interpolation
What is Interpolation? Interpolation is a method of finding new data points within the range of a discrete set of known data points (Source Wiki). In other words interpolation is the technique to estimate the value of a mathematical function, for any intermediate value of the independent variable. For example, in the given table we're given 4 set o
7 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg