Swift Program to Implement Interpolation Search

Swift Program to Implement Interpolation Search

Interpolation Search is a fascinating searching technique that gives you a smarter way to locate values inside a sorted list. While Binary Search always looks at the middle of the list, Interpolation Search tries to guess where the value might be based on its actual size. This makes it especially useful when your data is spread out in a predictable way, such as evenly spaced numbers or values that grow steadily. For beginners in Swift, it is a great way to understand how searching can become more efficient when the algorithm has a better idea of where to look.

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

What makes Interpolation Search interesting is the way it blends simple math with traditional searching. Instead of cutting the search space in half, it estimates the position using the relationship between the target and the data range. This can lead to very fast results if the data is uniform. While it does not replace Binary Search for all situations, it is an important tool to know and one that teaches how smarter guesses can lead to quicker answers.

Program 1: Basic Iterative Interpolation Search

This first program shows a simple and clear iterative version of Interpolation Search. It scans a sorted array by calculating a likely position using the target value and the range of numbers. This version is ideal for beginners because it closely follows the core idea of the algorithm.

import Foundation

func interpolationSearch(_ array: [Int], target: Int) -> Int {

    var low = 0
    var high = array.count - 1

    while low <= high && target >= array[low] && target <= array[high] {

        if low == high {
            return array[low] == target ? low : -1
        }

        let pos = low + (target - array[low]) * (high - low) / (array[high] - array[low])

        if array[pos] == target {
            return pos
        }

        if array[pos] < target {
            low = pos + 1
        } else {
            high = pos - 1
        }

    }

    return -1

}

let data1 = [5, 10, 15, 20, 25, 30, 35]

print("Found at index:", interpolationSearch(data1, target: 25))

This version works by narrowing down the range in a smart way. The position calculation uses interpolation to guess how far the target might be along the list. When the data is evenly spaced, the search becomes extremely fast, often faster than Binary Search. Beginners can study how the formula predicts the position and see how the range shrinks with each step.

Program 2: Recursive Interpolation Search

This version uses recursion instead of loops. It behaves the same way but expresses the logic through repeated function calls. Many learners find this style easier to understand because each call handles only a small part of the problem.

import Foundation

func interpolationSearchRecursive(_ array: [Int], target: Int, low: Int, high: Int) -> Int {

    if low > high || target < array[low] || target > array[high] {
        return -1
    }

    let pos = low + (target - array[low]) * (high - low) / (array[high] - array[low])

    if array[pos] == target {
        return pos
    }

    if array[pos] < target {
        return interpolationSearchRecursive(array, target: target, low: pos + 1, high: high)
    }

    return interpolationSearchRecursive(array, target: target, low: low, high: pos - 1)

}

let data2 = [2, 6, 10, 14, 18, 22, 26]

print("Found at index:", interpolationSearchRecursive(data2, target: 18, low: 0, high: data2.count - 1))

Because it breaks the work into smaller pieces, the recursive version makes the flow of the algorithm easier to follow. Each call narrows the search space until it finds the target or reaches an empty range. Beginners get a better sense of how recursion allows problems to shrink naturally.

Program 3: Interpolation Search with Floating-Point Numbers

This version adapts the algorithm for arrays of Double values. The main challenge with floating-point numbers is working with non-integers, but the structure remains almost the same.

import Foundation

func interpolationSearchDouble(_ array: [Double], target: Double) -> Int {

    var low = 0
    var high = array.count - 1

    while low <= high && target >= array[low] && target <= array[high] {

        if array[high] == array[low] {
            return array[low] == target ? low : -1
        }

        let pos = low + Int((target - array[low]) / (array[high] - array[low]) * Double(high - low))

        if array[pos] == target {
            return pos
        }

        if array[pos] < target {
            low = pos + 1
        } else {
            high = pos - 1
        }

    }

    return -1

}

let data3 = [1.2, 2.5, 3.8, 5.0, 6.1, 7.9]

print("Found at index:", interpolationSearchDouble(data3, target: 5.0))

Here the math uses floating-point division, allowing the algorithm to guess the right position even with decimal values. This version shows how flexible Interpolation Search becomes when adapted for real-world numeric data. Beginners can see that the algorithm’s structure stays the same even when the number type changes.

Program 4: Interpolation Search Inside a Struct Array

Sometimes your data comes in the form of objects, not simple numbers. This version shows how to perform Interpolation Search on a list of structs by using one of their properties as the search key.

import Foundation

struct Player {
    let name: String
    let score: Int
}

func interpolationSearchPlayers(_ players: [Player], target: Int) -> Int {

    var low = 0
    var high = players.count - 1

    while low <= high && target >= players[low].score && target <= players[high].score {

        let pos = low + (target - players[low].score) * (high - low) / (players[high].score - players[low].score)

        if players[pos].score == target {
            return pos
        }

        if players[pos].score < target {
            low = pos + 1
        } else {
            high = pos - 1
        }

    }

    return -1

}

let players = [
    Player(name: "Alice", score: 10),
    Player(name: "Bobby", score: 20),
    Player(name: "Carla", score: 30),
    Player(name: "Derek", score: 40)
]

print("Found at index:", interpolationSearchPlayers(players, target: 30))

This example shows how the algorithm adapts to more complex data. Instead of searching raw numbers, it looks at a property inside each object. Beginners will see how searching inside custom types works by applying the same logic to the chosen key.

Program 5: Interpolation Search for Evenly Distributed Large Data

This version demonstrates how Interpolation Search shines with large, uniform datasets. Instead of using a strange target value, this example searches for a number that actually makes sense within the range.

import Foundation

let largeData = Array(stride(from: 0, through: 100000, by: 10))

func interpolationSearchLarge(_ array: [Int], target: Int) -> Int {

    var low = 0
    var high = array.count - 1

    while low <= high && target >= array[low] && target <= array[high] {

        if array[high] == array[low] {
            return array[low] == target ? low : -1
        }

        let pos = low + (target - array[low]) * (high - low) / (array[high] - array[low])

        if array[pos] == target {
            return pos
        }

        if array[pos] < target {
            low = pos + 1
        } else {
            high = pos - 1
        }

    }

    return -1

}

print("Found at index:", interpolationSearchLarge(largeData, target: 45000))

This example highlights the speed of Interpolation Search when the data is evenly spaced. The algorithm can jump almost directly to the right spot, making the search extremely efficient. Beginners will appreciate how predictable data patterns help the algorithm perform at its best.

Frequently Asked Questions (FAQ)

This section answers the most common questions beginners usually have when learning Interpolation Search in Swift.

A1. Does Interpolation Search only work on sorted data?
Yes, it does. Interpolation Search depends on the values being in sorted order so it can guess the likely position of the target. Without sorted data, the formula it uses would not make sense, and the algorithm would not know where to move next.

A2. Is it faster than Binary Search?
It can be faster, but only in special cases. When the data is sorted and the values are spread out in a fairly even way, Interpolation Search can find items with fewer steps than Binary Search. But if the data is uneven or has clustered values, Binary Search is more reliable.

A3. What happens if the data is not evenly distributed?
If the values are not evenly distributed, the position formula becomes less accurate. This makes the algorithm jump to the wrong places and take more steps than expected. In the worst case, it might even become slower than simple Linear Search.

A4. Can Interpolation Search work with strings in Swift?
Not directly. The algorithm needs numeric values to calculate the estimated position. Strings would need to be converted into numbers first, such as by using ASCII values or some custom mapping. Even then, it will not be as accurate as using numbers that already have a natural numeric pattern.

A5. Why does the algorithm use a formula instead of checking the middle?
Interpolation Search tries to be smart by predicting where the target should be, instead of always checking the middle like Binary Search. It uses the formula to jump closer to the value it wants based on how the numbers are spread out. This can save time when the data follows a smooth numeric pattern.

Conclusion

Interpolation Search is a powerful example of how a little bit of math can make searching much faster when the data behaves in a predictable way. It teaches an important lesson about using the nature of the data to improve performance. While it does not replace Binary Search in every situation, it is an excellent tool to add to your Swift learning journey. The programs in this article give you a variety of ways to understand and practice the algorithm, from simple integers to large datasets and even custom structures. With more practice, you will gain an even stronger intuition for how smart searching techniques improve the speed of your Swift programs.

Scroll to Top