[Ruby] Implement the algorithm in Ruby: Day 4-Linear Search-

1 minute read

It left for three days and it continued for four days. The third day is here <Implementing the algorithm in Ruby: Day 3 -Binary search->

What is linear search

A method to find a specific value by comparing random data one by one from the beginning. If found, the process ends there. It’s a very simple algorithm If you understand how it works, move to coding immediately



# Linear search

def linerSearch(data, target)
  bool = -1
  count = 0
  while count <= data.length
    if data[count] == target
      bool = count
    count += 1

# Execute
print "Value to store:"
data = gets.split().map(&:to_i)
print "Search value:"
target = gets.to_i
search = linerSearch(data, target)

if search >= 0
  puts "#{target} was found at #{search+1}".
  puts "#{target} was not found."

linerSearch takes an array containing numbers and a search value as arguments. Loop until count, which indicates the position of the array, exceeds the size of the array If data is found, the location of the array at that time is assigned to bool and the loop ends. If not found, bool returns -1.

The location where the output is found if found. If not found, the fact that it was not found is output.


After all it was much easier than yesterday However, sometimes it is difficult to implement what you have in mind as you imagine.

By the way, next time we will try the most famous tower of Hanoi, which is recursion. .. ..