Lua - Linear Search



Linear Search is one of the fundamental and quite easy to implement searching algorithm. In linear search, we sequentially check each element in the list until we found a match or entire list is iterated.

main.lua

-- function to do a linear search
function linear_search(list, item)
  -- iterate over all elements of the list
  for i = 1, #list do
      -- if element is found
    if list[i] == item then
      return i -- Return the index
    end
  end
  return nil -- Return nil as item not found
end

-- Example Usage
local numbers = {5, 2, 8, 1, 9, 4}
local item = 8
local index = linear_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 = linear_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 Linear Search

  • Iterate through each element − We've started loop from 1st element to last element. If element is found, the index is returned.

  • 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. As item is not present, all elements are to be traversed.

  • Best Case O(1) − where item is the first element of the list.

  • Average Case O(n) − generally linear search is proportional to the number of items present in the list.

Space Complexity

  • O(1) − Space complexity of linear search is constant as it is not requiring any extra memory from the list for any temporary storage.

When to use Linear Search

Linear search is simple and easy to implement and is used in following areas −

  • When list is small in size.

  • When list elements are not sorted.

  • When we need to implement a simple algorithm for example, for educational purposes.

Advertisements