C++ Program to Implement Interpolation Search

C++ Program to Implement Interpolation Search

Searching efficiently in an array is one of the core skills in C++ programming. While many beginners start with linear or binary search, interpolation search is a smarter alternative for sorted, evenly distributed arrays. Unlike binary search, which always splits the search space in half, interpolation search estimates where the target element might be, saving time and comparisons in the process. It’s like guessing the page number of a chapter based on the page numbers at the start and end of the book, rather than flipping blindly to the middle.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

This search algorithm is especially useful in real-world applications, such as database indexing, record retrieval, and numerical datasets where values are spread evenly. For beginners, understanding interpolation search is a great way to grasp how algorithms can use patterns in data to optimize performance. It’s not just about finding a number—it’s about learning how algorithms think.

Program 1: Iterative Interpolation Search

This program demonstrates the loop-based approach to interpolation search. It is straightforward, making it ideal for beginners who want to understand the algorithm step by step.

#include <iostream>

using namespace std;

int interpolationSearch(int arr[], int n, int key) {

    int low = 0;
    int high = n - 1;

    while (low <= high && key >= arr[low] && key <= arr[high]) {

        if (low == high) {
            if (arr[low] == key) return low;
            return -1;
        }

        int pos = low + ((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low]);

        if (arr[pos] == key)
            return pos;
        if (arr[pos] < key)
            low = pos + 1;
        else
            high = pos - 1;

    }

    return -1;

}

int main() {

    int arr[] {10, 20, 30, 40, 50, 60, 70, 80, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 70;

    int index = interpolationSearch(arr, n, key);

    if (index != -1)
        cout << "Element found at index: " << index << endl;
    else
        cout << "Element not found." << endl;

    return 0;

}

This iterative program calculates the estimated position of the target using a simple formula and loops until it finds the key. Beginners can learn how estimating positions reduces unnecessary comparisons compared to linear search.

Program 2: Recursive Interpolation Search

Recursion offers a clean, elegant way to implement interpolation search. This program shows how the search can call itself for smaller subarrays.

#include <iostream>

using namespace std;

int interpolationSearchRecursive(int arr[], int low, int high, int key) {

    if (low <= high && key >= arr[low] && key <= arr[high]) {

        if (low == high) {
            if (arr[low] == key) return low;
            return -1;
        }

        int pos = low + ((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low]);

        if (arr[pos] == key)
            return pos;
        if (arr[pos] < key)
            return interpolationSearchRecursive(arr, pos + 1, high, key);
        else
            return interpolationSearchRecursive(arr, low, pos - 1, key);

    }

    return -1;

}

int main() {

    int arr[] {5, 15, 25, 35, 45, 55, 65, 75, 85};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 55;

    int index = interpolationSearchRecursive(arr, 0, n - 1, key);

    if (index != -1)
        cout << "Element found at index: " << index << endl;
    else
        cout << "Element not found." << endl;

    return 0;

}

The recursive approach emphasizes breaking problems into smaller subproblems, a concept beginners often find valuable. It performs the same search but in a cleaner, more structured style.

Program 3: User Input for Interpolation Search

This example shows how beginners can combine interpolation search with user input, making the program interactive and practical.

#include <iostream>

using namespace std;

int interpolationSearch(int arr[], int n, int key) {

    int low = 0;
    int high = n - 1;

    while (low <= high && key >= arr[low] && key <= arr[high]) {

        int pos = low + ((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low]);

        if (arr[pos] == key)
            return pos;
        if (arr[pos] < key)
            low = pos + 1;
        else
            high = pos - 1;

    }

    return -1;

}

int main() {

    int arr[] {2, 4, 6, 8, 10, 12, 14, 16};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key;

    cout << "Enter the number to search: ";
    cin >> key;

    int index = interpolationSearch(arr, n, key);

    if (index != -1)
        cout << "Element found at index: " << index << endl;
    else
        cout << "Element not found." << endl;

    return 0;

}

This approach reinforces how to integrate algorithms with dynamic user input, helping beginners see real-world applications and interaction in programs.

Program 4: Safe Interpolation Search with Error Handling

Real applications often require robust error handling. This version ensures the search doesn’t break with invalid positions.

#include <iostream>

using namespace std;

int safeInterpolationSearch(int arr[], int n, int key) {

    int low = 0, high = n - 1;

    while (low <= high && key >= arr[low] && key <= arr[high]) {

        if (arr[high] == arr[low]) break;

        int pos = low + ((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low]);

        if (pos < 0 || pos >= n) return -1;

        if (arr[pos] == key)
            return pos;
        if (arr[pos] < key)
            low = pos + 1;
        else
            high = pos - 1;

    }

    return -1;

}

int main() {

    int arr[] {3, 6, 9, 12, 15, 18, 21};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 18;

    int index = safeInterpolationSearch(arr, n, key);

    if (index != -1)
        cout << "Element found at index: " << index << endl;
    else
        cout << "Element not found or invalid input." << endl;

    return 0;

}

Adding checks makes the program more reliable and beginner-friendly, showing that safety is just as important as efficiency in programming.

Program 5: Interpolation Search for Large Arrays

Here, we demonstrate the efficiency of interpolation search on larger datasets, ideal for understanding its performance benefits.

#include <iostream>

using namespace std;

int interpolationSearch(int arr[], int n, int key) {

    int low = 0, high = n - 1;

    while (low <= high && key >= arr[low] && key <= arr[high]) {

        int pos = low + ((double)(high - low) / (arr[high] - arr[low])) * (key - arr[low]);

        if (arr[pos] == key)
            return pos;
        if (arr[pos] < key)
            low = pos + 1;
        else
            high = pos - 1;

    }

    return -1;

}

int main() {

    int arr[100];

    for(int i = 0; i < 100; i++) arr[i] = i * 10;

    int key = 780;

    int index = interpolationSearch(arr, 100, key);

    if (index != -1)
        cout << "Element found at index: " << index << endl;
    else
        cout << "Element not found." << endl;

    return 0;

}

For beginners, this program illustrates how interpolation search can efficiently handle larger arrays, especially when the values are evenly spaced. It’s a perfect way to visualize performance improvement over simpler searches.

Frequently Asked Questions (FAQ)

Here are some questions beginners often ask about interpolation search:

Q1: What is the difference between binary search and interpolation search?
Binary search always checks the middle element, while interpolation search estimates the likely position based on the values at the start and end. This can make it faster for uniformly distributed arrays.

Q2: Can interpolation search be used on unsorted arrays?
No. The array must be sorted; otherwise, the estimated position won’t be reliable.

Q3: When is interpolation search most effective?
It works best for large, evenly distributed datasets. Irregular or skewed data may make binary search more reliable.

Q4: Is recursion necessary in interpolation search?
No, both iterative and recursive methods work. Recursion just offers a cleaner code structure.

Q5: How does interpolation search handle duplicates?
It may find one occurrence, but not all duplicates. Additional logic is needed to handle multiple identical elements.

Conclusion

Interpolation search is a powerful algorithm for quickly finding elements in sorted, evenly spaced arrays. Through iterative, recursive, and practical programs, beginners can see how smart estimation reduces the number of comparisons compared to simple searches. By experimenting with user input, error handling, and larger arrays, you can strengthen your understanding and gain confidence in applying this algorithm to real-world problems. Keep practicing, explore different variations, and soon interpolation search will become a natural part of your C++ toolkit.

Scroll to Top