Lua - Jump Search
Jump Search or Block Search is searh algorithm on sorted lists. It works by skipping by fixed size of steps and then performing a linear search on the block where item can be found.
main.lua
-- function to search an item in the list
function jump_search(list, item)
local n = #list -- size of the list
local step = math.floor(math.sqrt(n)) -- steps to skip
local prev = 1
-- Find the block where the item can be found
while prev < n and list[math.min(step, n)] < item do
prev = step
step = step + math.floor(math.sqrt(n))
end
-- Perform linear search in the block
while prev <= math.min(step, n) do
if list[prev] == item then
return prev
end
prev = prev + 1
end
return nil -- Return nil if the item is not found
end
-- Example Usage
local numbers = {1, 2, 4, 5, 8, 9}
local item = 8
local index = jump_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 = jump_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 Jump Search
Initialize a Step − We've initialized a step as &sqrt;n where n is number of items.
Compute the block − Now we're incrementing the steps as per block size(&sqrt;n) to skip till numbers are smaller than item to searched.
Iterate sub list − Remaining items are searched using a linear search.
Not found − If complete list is iterated and item is not found then we're returning nil.
Time Complexity
Worst Case, Best Case and Average Case O(&sqrt;n) − where n is number of elements. A block is jumped based on computation of steps to skip.
Space Complexity
O(1) − Space complexity of jump search is constant as it is not requiring any extra memory from the list for any temporary storage.
When to use Jump Search
Jump search is very efficient and used in following areas −
When list is sorted.
When access to element is costly as jump search jumps fewer times as compared to binary search.