Linear Search Algorithm in Ruby

1. Introduction

Linear search, also known as sequential search, is a straightforward method for finding a specific value in a list. It checks each element of the list sequentially until the desired value is found or until all the elements have been checked. While it's simple to implement, it's not the most efficient search algorithm for large datasets.

2. Implementation Steps

1. Start from the first element of the list.

2. Compare the desired value with the current element.

3. If they match, return the current index.

4. If they do not match, move to the next element.

5. Repeat steps 2-4 until the desired value is found or until the end of the list is reached.

3. Implementation in Ruby Programming

def linear_search(array, value_to_find)
  array.each_with_index do |element, index|
    return index if element == value_to_find  # Return the index if the element is found
  end
  return nil  # Return nil if the element is not found
end
# Client code
arr = [12, 34, 54, 2, 3]
value = 54
puts "Array: #{arr}"
index = linear_search(arr, value)
if index
  puts "#{value} found at index #{index}"
else
  puts "#{value} not found in the array"
end

Output:

Array: [12, 34, 54, 2, 3]
54 found at index 2

Explanation:

1. Linear search is a simple search algorithm that checks every element of a list until it finds the desired value or exhausts the list.

2. It doesn't require the list to be sorted.

3. The algorithm iterates over the list and compares the desired value with the current element.

4. If a match is found, it returns the index of the matched element.

5. If no match is found by the end of the list, it returns nil or indicates the absence of the value in the list.

6. While linear search is easy to implement, it's not optimal for large lists as it can take a long time in the worst case.


Comments