Kotlin Program to Implement Interpolation Search

Kotlin Program to Implement Interpolation Search

Searching is a fundamental part of programming, and finding efficient ways to locate elements can save time, especially with large datasets. Interpolation Search is a search algorithm similar to Binary Search, but it improves performance when elements are uniformly distributed. Instead of always checking the middle element like in Binary Search, Interpolation Search estimates the likely position of the target using a formula, which often allows it to find elements faster.

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 is particularly useful in real-world scenarios where values are evenly spaced, such as ID numbers, salaries, or temperatures recorded over time. For beginners learning Kotlin, this algorithm is an excellent way to explore more advanced searching techniques beyond simple linear or binary searches. By understanding Interpolation Search, you also get a practical introduction to mathematical formulas in programming and how to use them to optimize algorithms.

Program 1: Iterative Interpolation Search on Array

This program demonstrates the classic iterative approach to Interpolation Search, where the estimated position of the target is calculated in each step.

fun interpolationSearch(arr: IntArray, target: Int): Int {

    var low = 0
    var high = arr.size - 1

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

        if (low == high) {
            return if (arr[low] == target) low else -1
        }

        val pos = low + ((target - arr[low]) * (high - low) / (arr[high] - arr[low]))

        when {

            arr[pos] == target -> return pos
            arr[pos] < target -> low = pos + 1
            else -> high = pos - 1

        }

    }

    return -1

}

fun main() {

    val numbers = intArrayOf(10, 20, 30, 40, 50, 60, 70)
    val target = 40

    println("Array: ${numbers.joinToString()}")

    val index = interpolationSearch(numbers, target)

    if (index != -1) println("Element $target found at index $index")
    else println("Element $target not found")

}

In this approach, the formula calculates an estimated position (pos) based on the target value and the values at the current bounds. This reduces unnecessary comparisons, making it faster than linear search for uniformly distributed data. Beginners can see how math can directly guide algorithm efficiency.

Program 2: Recursive Interpolation Search

Interpolation Search can also be implemented recursively, which shows a clean divide-and-conquer approach.

fun interpolationSearchRecursive(arr: IntArray, target: Int, low: Int = 0, high: Int = arr.size - 1): Int {

    if (low > high || target < arr[low] || target > arr[high]) return -1

    val pos = low + ((target - arr[low]) * (high - low) / (arr[high] - arr[low]))

    return when {

        arr[pos] == target -> pos
        arr[pos] < target -> interpolationSearchRecursive(arr, target, pos + 1, high)
        else -> interpolationSearchRecursive(arr, target, low, pos - 1)

    }

}

fun main() {

    val numbers = intArrayOf(5, 15, 25, 35, 45, 55)
    val target = 25

    println("Array: ${numbers.joinToString()}")

    val index = interpolationSearchRecursive(numbers, target)

    if (index != -1) println("Element $target found at index $index")
    else println("Element $target not found")

}

The recursive version works by estimating the position and narrowing the search range each time. This helps beginners understand recursion and how dividing the problem can simplify complex searches.

Program 3: Interpolation Search on Kotlin List

Interpolation Search is not limited to arrays; it can also be applied to Kotlin lists. This program demonstrates searching on a List<Int>.

fun interpolationSearchList(list: List<Int>, target: Int): Int {

    var low = 0
    var high = list.size - 1

    while (low <= high && target >= list[low] && target <= list[high]) {

        if (low == high) return if (list[low] == target) low else -1

        val pos = low + ((target - list[low]) * (high - low) / (list[high] - list[low]))

        when {

            list[pos] == target -> return pos
            list[pos] < target -> low = pos + 1
            else -> high = pos - 1

        }

    }

    return -1

}

fun main() {

    val numbers = listOf(2, 4, 6, 8, 10, 12)
    val target = 8

    println("List: $numbers")

    val index = interpolationSearchList(numbers, target)

    if (index != -1) println("Element $target found at index $index")
    else println("Element $target not found")

}

This example shows that Kotlin collections can work with the algorithm without any major changes, making it versatile for real applications.

Program 4: Interpolation Search with Duplicate Elements

When arrays have duplicate elements, you might want to find the first occurrence of a target. This version adjusts the search to locate the first instance.

fun interpolationSearchFirst(arr: IntArray, target: Int): Int {

    var low = 0
    var high = arr.size - 1
    var result = -1

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

        val pos = low + ((target - arr[low]) * (high - low) / (arr[high] - arr[low]))

        when {

            arr[pos] == target -> {
                result = pos
                high = pos - 1
            }

            arr[pos] < target -> low = pos + 1
            else -> high = pos - 1

        }

    }

    return result

}

fun main() {

    val numbers = intArrayOf(10, 20, 20, 30, 40)
    val target = 20

    println("Array: ${numbers.joinToString()}")

    val index = interpolationSearchFirst(numbers, target)

    if (index != -1) println("First occurrence of $target is at index $index")
    else println("$target not found")

}

This program highlights how Interpolation Search can be modified for specific requirements, like handling duplicates, which is useful in real-world applications.

Frequently Asked Questions (FAQ)

Here are common questions beginners ask about Interpolation Search in Kotlin.

Q1: What is Interpolation Search?
Interpolation Search is a search algorithm that estimates the likely position of the target using a formula, making it faster for uniformly distributed data.

Q2: When should I use Interpolation Search?
It is ideal for large, sorted, and evenly distributed datasets where Binary Search may not be the most efficient.

Q3: Can Interpolation Search handle lists and arrays?
Yes, it works for both arrays and Kotlin lists without major changes.

Q4: What is the time complexity?
The average time complexity is O(log log n) for uniform distributions, but the worst case is O(n).

Q5: Can it be implemented recursively?
Yes, recursion is possible and can make the code more elegant by reducing the search range each time.

Conclusion

Interpolation Search is an advanced searching algorithm that improves efficiency over linear search for evenly distributed data. In Kotlin, it can be implemented iteratively, recursively, and applied to arrays or lists. Beginners learning this algorithm will gain a strong understanding of how mathematical estimation can optimize search operations, as well as how to adapt algorithms for duplicates and specific requirements. By practicing these variations, you can develop more efficient and robust search solutions in real-world Kotlin applications.

Scroll to Top