Java Program to Implement Interpolation Search

Java Program to Implement Interpolation Search

Searching for data efficiently is one of the most important topics in computer programming. Whether you’re building a small application or a complex system, you’ll often need to look for specific values within large sets of data. While basic algorithms like linear search and binary search are quite popular, there’s another elegant and faster method when data is sorted and uniformly distributed — it’s called Interpolation Search.

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

Interpolation Search works a bit like how humans guess the position of a number in a sorted list. For example, if you are looking for a price of 85 in a list of prices from 10 to 100, you might not start in the middle but closer to where 85 would likely be. This approach makes interpolation search very efficient for evenly spaced data, as it reduces the number of comparisons needed to find the target element. In this article, we’ll explore multiple ways to implement Interpolation Search in Java — from simple loops to recursive and more advanced versions.

Program 1: Basic Iterative Interpolation Search in Java

This first program demonstrates a simple loop-based interpolation search. It’s easy to understand and perfect for beginners learning how the algorithm works step by step.

public class InterpolationSearchExample1 {

    public static int interpolationSearch(int[] arr, int x) {

        int low = 0;
        int high = arr.length - 1;

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

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

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

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50, 60, 70};
        int x = 40;
        int result = interpolationSearch(numbers, x);

        if (result != -1)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found");

    }

}

This program uses a while loop to calculate the estimated position of the element using the interpolation formula. It narrows down the range based on where the value is likely located. Beginners can think of it as a smarter version of binary search, where the algorithm “guesses” the position more accurately in uniform data.

Program 2: Recursive Interpolation Search in Java

This version shows how you can use recursion to perform interpolation search. It’s ideal for learners who want to understand how recursive functions can replace loops.

public class InterpolationSearchExample2 {

    public static int interpolationSearch(int[] arr, int low, int high, int x) {

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

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

            if (arr[pos] == x)
                return pos;
            if (arr[pos] < x)
                return interpolationSearch(arr, pos + 1, high, x);

            return interpolationSearch(arr, low, pos - 1, x);

        }

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = {5, 15, 25, 35, 45, 55, 65};
        int x = 55;
        int result = interpolationSearch(arr, 0, arr.length - 1, x);

        if (result != -1)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found");

    }

}

The recursive approach divides the search into smaller calls until the element is found or the range is exhausted. It’s elegant and simple to read. Beginners should note that recursion can make code cleaner, though iterative methods often perform better for large datasets due to lower memory usage.

Program 3: Interpolation Search with Floating-Point Numbers

This version works with arrays of floating-point numbers instead of integers. It’s useful when dealing with data like prices, measurements, or ratings.

public class InterpolationSearchExample4 {

    public static int interpolationSearch(double[] arr, double x) {

        int low = 0, high = arr.length - 1;

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

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

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

        }

        return -1;

    }

    public static void main(String[] args) {

        double[] arr = {1.5, 2.3, 3.7, 4.1, 5.9, 7.4, 9.0};
        double x = 5.9;
        int result = interpolationSearch(arr, x);

        if (result != -1)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found");

    }

}

This program teaches beginners that interpolation search is not limited to integers. As long as the data is sorted and uniformly distributed, it works just as well with floating-point numbers.

Program 4: Interpolation Search with User Input

In this program, we allow the user to enter their own array and target value. It helps beginners see how to handle input while performing interpolation search.

import java.util.Scanner;

public class InterpolationSearchExample3 {

    public static int interpolationSearch(int[] arr, int x) {

        int low = 0, high = arr.length - 1;

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

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

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

        }

        return -1;

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter size of array: ");
        int size = scanner.nextInt();

        int[] arr = new int[size];

        System.out.println("Enter sorted array elements:");

        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }

        System.out.print("Enter element to search: ");
        int x = scanner.nextInt();

        int result = interpolationSearch(arr, x);

        if (result != -1)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found");

        scanner.close();

    }

}

This version is practical because it allows users to experiment with their own data. Beginners can easily test how interpolation search behaves with different sets of numbers, giving them hands-on experience.

Program 5: Enhanced Interpolation Search with Validation

This advanced version adds data validation and handles cases where the array is not uniformly distributed or may cause division errors.

public class InterpolationSearchExample5 {

    public static int interpolationSearch(int[] arr, int x) {

        int low = 0, high = arr.length - 1;

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

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

            if (pos < 0 || pos >= arr.length)
                return -1;

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

        }

        return (arr[low] == x) ? low : -1;

    }

    public static void main(String[] args) {

        int[] arr = {10, 20, 30, 40, 50, 60, 70};
        int x = 60;
        int result = interpolationSearch(arr, x);

        if (result != -1)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found");

    }

}

This final version is more robust and can handle edge cases safely. It checks for invalid positions and avoids division by zero errors. Beginners will find it useful for understanding how to make algorithms more reliable in real-world applications.

Frequently Asked Questions (FAQ)

This section answers common questions beginners often have about Interpolation Search in Java.

Q1: What is the main difference between Binary Search and Interpolation Search?
A1: Binary search always checks the middle element, while interpolation search estimates the position based on the target value. This makes interpolation search faster on uniformly distributed data.

Q2: Can Interpolation Search work on unsorted data?
A2: No, it requires a sorted array to function correctly. Without sorting, the estimated position will be inaccurate.

Q3: Is Interpolation Search faster than Binary Search?
A3: In the best cases, yes. Interpolation Search can have a time complexity of O(log log n) for uniformly distributed data, compared to Binary Search’s O(log n). However, in the worst case, it may degrade to O(n).

Q4: When should I use Interpolation Search?
A4: Use it when the data is sorted and uniformly distributed — for example, searching prices, grades, or timestamps that follow a steady pattern.

Q5: Can I use Interpolation Search for strings?
A5: Not directly. It’s designed for numeric values. For strings, binary search or hashing methods are more suitable.

Conclusion

Interpolation Search in Java is an elegant and efficient algorithm when working with sorted, evenly distributed data. It estimates where a value might be based on its comparison with the range of the dataset, often reducing the number of comparisons needed. In this article, we covered different ways to implement it — using loops, recursion, user input, floating-point arrays, and enhanced validation.

As you practice these programs, you’ll gain a deeper understanding of how search algorithms work and how to choose the right one for your data. Keep experimenting, tweak the code, and soon you’ll be able to uuse interpolation search confidently in real-world applications.

Scroll to Top