Lua - Interpolation Search
Interpolation search is an improved version of binary search. Where binary search algorithm searches by checking the middle element after dividing a sorted list into two halves, interpolation search estimates the position of item to be searched based on its value closer to the bounds.
main.lua
-- function to search an item in the list
function interpolation_search(list, item)
local low = 1
local high = #list
-- loop until item is in between low and high indices
while low <= high and item >= list[low] and item <= list[high] do
-- if item is found, return the index
if low == high then
if list[low] == item then
return low
else
return nil
end
end
-- Estimate the position by interpolation
local pos = low + math.floor(((high - low) / (list[high] - list[low])) * (item - list[low]))
-- if item is found else update low and high accordingly
if list[pos] == item then
return pos
elseif list[pos] < item then
low = pos + 1
else
high = pos - 1
end
end
return nil
end
-- Example Usage
local numbers = {1, 2, 4, 5, 8, 9}
local item = 8
local index = interpolation_search(numbers, item)
if index then
print("Item", item, "found, index:", index) -- Output: Item 8 found at index: 3
else
print("Item", item, "not found in the list.")
end
item = 3
index = interpolation_search(numbers, item)
if index then
print("Item", item, "found at index:", index)
else
print("Item", item, "not present.") -- Output: Item 3 not found in the list.
end
Output
When we run the above program, we will get the following output−
Item 8 found, index: 3 Item 3 not present.
Working of Interpolation Search
low and high − We've initialized low as 1 and high as list length as initial list indexes. A loop is run till low becomes same or higher than high and item to be searched is within low and high indices.
Divide the list into two halves based on interpolated index − A value is interpolated based on uniformity of the data.
Iterate sub list − Above steps are repeated for sublists after computing low and high.
Not found − If complete list is iterated and item is not found then we're returning nil.
Time Complexity
Worst Case O(n) − where n is number of elements. In case data is not uniformly distributed.
Best Case O(log n) − for uniformly distributed data.
Average Case O(log n) − Interpolation search halved the items to be searched in each iteration.
Space Complexity
O(1) − Space complexity of interpolation search is constant as it is not requiring any extra memory from the list for any temporary storage.
When to use Interpolation Search
Interpolation search is very efficient and used in following areas −
When list is sorted.
When we've uniformly distributed data. Interpolation search is faster than even binary searches in such case.