Implement the algorithm in Ruby: Day 4-Linear search-

It lasted for 4 days after leaving the shaven for 3 days. Click here for the 3rd day <Implementing the algorithm in Ruby: Day 3 -Binary search->

What is a linear search?

A method of finding 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. Let's move on to coding as soon as we understand the mechanism



#Linear search

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

print "Value to store:"
data = gets.split().map(&:to_i)
print "Value to look for:"
target = gets.to_i
search = linerSearch(data, target)

if search >= 0
  puts "#{target}Is#{search+1}Found second."
  puts "#{target}Was not found."

linerSearch takes an array of numbers and the value to look for as arguments. Loop until count indicating the position of the array exceeds the size of the array If data is found, assign the location of the array at that time to bool and end the loop. If not found, bool returns -1.

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


After all it was very easy compared to yesterday However, I sometimes find it difficult to implement what I can imagine as I imagined.

Next time, let's try the Tower of Hanoi, which is the most famous for recursion. .. ..

Recommended Posts

Implement the algorithm in Ruby: Day 4-Linear search-
Binary search method
Implement the algorithm in Ruby: Day 4-Linear search-
Implement the algorithm in Ruby: Day 2 -Bubble sort-
I tried to implement the Euclidean algorithm in Java
Implement a gRPC client in Ruby
Implemented basic search / sort algorithm in Java
How to build the simplest blockchain in Ruby
How to implement Pagination in GraphQL (for ruby)
I want to get the value in Ruby
Heavy in Ruby! ??
Get the URL of the HTTP redirect destination in Ruby