2021-02-07 08:05:54 +01:00
|
|
|
# Looks through array for a value in O(n) time.
|
|
|
|
# Array does not need to be sorted.
|
2017-10-01 19:56:35 +02:00
|
|
|
def linear_search(array, key)
|
|
|
|
array.each_with_index do |current, index|
|
|
|
|
return index if current == key
|
|
|
|
end
|
2021-02-07 08:05:54 +01:00
|
|
|
nil
|
2017-10-01 19:56:35 +02:00
|
|
|
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
|
2021-02-07 08:05:54 +01:00
|
|
|
puts if linear_search(arr, key) != nil
|
|
|
|
"Found at index #{linear_search(arr, key)}"
|
|
|
|
else
|
2017-10-01 19:56:35 +02:00
|
|
|
"Not found"
|
2021-02-07 08:05:54 +01:00
|
|
|
end
|