The Wayback Machine - https://web.archive.org/web/20240917060813/https://www.geeksforgeeks.org/g-fact-84/
Open In App

Interpolation search vs Binary search

Last Updated : 11 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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
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
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
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node 5 is a BST 5 / \ 4 6 Another BST we have is rooted
10 min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Anagram Substring Search (Or Search for all permutations) | Set 2
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Input: txt[] = "AAABABAA" p
10 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
15 min read
Article Tags :
Practice Tags :