Lua Program to Implement Interpolation Search

Lua Program to Implement Interpolation Search

Interpolation Search is an advanced searching algorithm that improves on the efficiency of Binary Search in certain situations. While Binary Search always checks the middle element of a sorted array, Interpolation Search estimates the likely position of the target based on its value. This makes it particularly effective for uniformly distributed datasets, where values are evenly spread out. For beginners, learning Interpolation Search is a great way to understand how smart guesses can speed up searching and why algorithm choice matters depending on the data.

In real-world applications, Interpolation Search is often used in systems that deal with numeric data, such as searching through large ordered lists of IDs, grades, or timestamps. Unlike simpler algorithms like Linear Search, which checks each element one by one, Interpolation Search reduces the number of comparisons dramatically, especially when the data is evenly distributed. By the end of this article, you will see multiple ways to implement Interpolation Search in Lua, including iterative and recursive approaches, and how it can handle different types of numbers.

Program 1: Iterative Interpolation Search

This first program demonstrates a basic iterative approach to Interpolation Search. It searches for a target value in a sorted array of numbers.

-- Iterative Interpolation Search in Lua

function interpolationSearch(arr, target)

    local low = 1
    local high = #arr

    while low <= high and target >= arr[low] and target <= arr[high] do

        if low == high then

            if arr[low] == target then
                return low
            else
                return -1
            end

        end

        local pos = low + math.floor(((high - low) / (arr[high] - arr[low])) * (target - arr[low]))

        if arr[pos] == target then
            return pos
        elseif arr[pos] < target then
            low = pos + 1
        else
            high = pos - 1
        end

    end

    return -1

end

local numbers = {10, 20, 30, 40, 50, 60, 70}
local target = 40
local result = interpolationSearch(numbers, target)

if result ~= -1 then
    print("Number found at position: " .. result)
else
    print("Number not found")
end

In this program, the position pos is calculated based on the value of the target relative to the current range. This allows the search to jump closer to the expected location rather than always checking the middle. Beginners can see how the formula uses simple math to make the search more efficient for evenly spaced numbers.

Program 2: Recursive Interpolation Search

This version demonstrates a recursive approach, which calls itself for smaller subarrays until the target is found or the range becomes invalid.

-- Recursive Interpolation Search in Lua

function recursiveInterpolationSearch(arr, target, low, high)

    low = low or 1
    high = high or #arr

    if low > high or target < arr[low] or target > arr[high] then
        return -1
    end

    if low == high then

        if arr[low] == target then
            return low
        else
            return -1
        end

    end

    local pos = low + math.floor(((high - low) / (arr[high] - arr[low])) * (target - arr[low]))

    if arr[pos] == target then
        return pos
    elseif arr[pos] < target then
        return recursiveInterpolationSearch(arr, target, pos + 1, high)
    else
        return recursiveInterpolationSearch(arr, target, low, pos - 1)
    end

end

local numbers = {5, 15, 25, 35, 45, 55}
local target = 35
local result = recursiveInterpolationSearch(numbers, target)

if result ~= -1 then
    print("Number found at index: " .. result)
else
    print("Number not found")
end

Recursion allows the function to repeatedly narrow down the range of the search without writing loops manually. Beginners can understand this as breaking the problem into smaller, similar subproblems until the solution is found.

Program 3: Interpolation Search with negative numbers

Interpolation Search works with negative numbers as long as the array is sorted. This program demonstrates searching in an array with negative and positive values.

-- Interpolation Search with negative numbers

function interpolationSearch(arr, target)

    local low = 1
    local high = #arr

    while low <= high and target >= arr[low] and target <= arr[high] do

        if low == high then

            if arr[low] == target then
                return low
            else
                return -1
            end

        end

        local pos = low + math.floor(((high - low) / (arr[high] - arr[low])) * (target - arr[low]))

        if arr[pos] == target then
            return pos
        elseif arr[pos] < target then
            low = pos + 1
        else
            high = pos - 1
        end

    end

    return -1

end

local numbers = {-50, -20, -10, 0, 10, 20, 30}
local target = -10
local result = interpolationSearch(numbers, target)

if result ~= -1 then
    print("Number found at index: " .. result)
else
    print("Number not found")
end

Beginners can see that the algorithm works the same way with negative values because it relies on comparison and proportional calculations rather than absolute positions.

Program 4: Interpolation Search with floating-point numbers

This program shows how Interpolation Search can handle arrays of floating-point numbers for more precise applications.

-- Interpolation Search with floating-point numbers

function interpolationSearch(arr, target)

    local low = 1
    local high = #arr

    while low <= high and target >= arr[low] and target <= arr[high] do

        if low == high then

            if arr[low] == target then
                return low
            else
                return -1
            end

        end

        local pos = low + math.floor(((high - low) / (arr[high] - arr[low])) * (target - arr[low]))

        if arr[pos] == target then
            return pos
        elseif arr[pos] < target then
            low = pos + 1
        else
            high = pos - 1
        end

    end

    return -1

end

local numbers = {0.5, 1.5, 2.5, 3.5, 4.5}
local target = 3.5
local result = interpolationSearch(numbers, target)

if result ~= -1 then
    print("Number found at index: " .. result)
else
    print("Number not found")
end

This example emphasizes that Interpolation Search is versatile and works with both integers and floating-point numbers without modifying the core algorithm.

Program 5: Reusable Interpolation Search function

This program wraps Interpolation Search into a reusable function suitable for any sorted numeric array. Beginners can integrate this into larger projects easily.

-- Reusable Interpolation Search function

function interpolationSearch(arr, target)

    local low = 1
    local high = #arr

    while low <= high and target >= arr[low] and target <= arr[high] do

        if low == high then

            if arr[low] == target then
                return low
            else
                return -1
            end

        end

        local pos = low + math.floor(((high - low) / (arr[high] - arr[low])) * (target - arr[low]))

        if arr[pos] == target then
            return pos
        elseif arr[pos] < target then
            low = pos + 1
        else
            high = pos - 1
        end

    end

    return -1

end

local numbers = {2, 4, 6, 8, 10, 12, 14}
local target = 8
local index = interpolationSearch(numbers, target)

if index ~= -1 then
    print("Target found at index: " .. index)
else
    print("Target not found")
end

This reusable function demonstrates how to keep code organized and ready for practical applications, making it beginner-friendly and easy to adapt.

Frequently Asked Questions (FAQ)

Interpolation Search is a powerful algorithm but can raise questions for beginners:

Q1. Can Interpolation Search work on unsorted arrays?
No, the array must be sorted for the algorithm to work correctly.

Q2. Is Interpolation Search faster than Binary Search?
It can be faster on uniformly distributed datasets because it estimates the likely position of the target.

Q3. Can Interpolation Search handle negative numbers and floats?
Yes, as long as the array is sorted and comparisons are valid, it works with all numeric types.

Q4. Should I use recursion or iteration?
Both approaches work. Iteration is generally more memory-efficient, while recursion can make the code cleaner.

Q5. When should I prefer Interpolation Search over Binary Search?
When the dataset is large, numeric, and uniformly distributed, Interpolation Search can outperform Binary Search in terms of speed.

Conclusion

Interpolation Search is a smart, efficient searching algorithm that improves on Binary Search by predicting the likely location of a target. In this article, we explored iterative and recursive implementations, and saw how it works with negative and floating-point numbers. By practicing these examples in Lua, beginners can understand how proportional calculations can optimize searches, build reusable functions, and improve their algorithmic thinking. Exploring Interpolation Search gives you another powerful tool for efficiently searching through numeric data in real-world applications.

Scroll to Top