linear search Algorithm

The linear search algorithm, also known as the sequential search algorithm, is a fundamental and straightforward method for searching an element in a list or an array. It works by iterating through each element in the list or array one-by-one, comparing the target value to each element until a match is found or the end of the list is reached. Linear search is considered a basic algorithm because of its simplicity and ease of implementation. It does not require any advanced data structures or pre-processing steps, making it universally applicable to any type of list or array. However, the primary disadvantage of the linear search algorithm is its inefficiency, particularly in large datasets. The algorithm has a worst-case time complexity of O(n), meaning that its execution time increases linearly with the size of the input data. In the worst case, the target element could be the last element in the list or not present at all, requiring a full traversal of the entire list. This can be problematic when dealing with substantial amounts of data or when the search operation needs to be performed frequently. In such cases, more advanced search algorithms, such as binary search, interpolation search, or hashing techniques, are often more suitable alternatives.
=begin
Looks through array for a value in O(n) time.
Array does not need to be sorted.
=end
def linear_search(array, key)
  array.each_with_index do |current, index|
    return index if current == key
  end
  return nil
end

puts "Enter a space-separated list:"
arr = gets.chomp.split(' ').map(&:to_i)
puts "Enter a value to be searched:"
key = gets.chomp.to_i
puts linear_search(arr, key) != nil ?
  "Found at index #{linear_search(arr, key)}" :
  "Not found"

LANGUAGE:

DARK MODE: