1
0
Fork 0
mirror of https://github.com/TheAlgorithms/Ruby synced 2025-01-28 19:58:20 +01:00
TheAlgorithms-Ruby/Searches/double_linear_search.rb

30 lines
628 B
Ruby
Raw Normal View History

2020-12-20 16:49:22 -08:00
# Iterate through the array from both sides to find the index of search_item.
def double_linear_search(array, search_item)
start_ind = 0
end_ind = array.length - 1
while start_ind <= end_ind
2020-12-20 16:50:42 -08:00
return start_ind if array[start_ind] == search_item
return end_ind if array[end_ind] == search_item
start_ind += 1
end_ind -= 1
2020-12-20 16:49:22 -08:00
end
# returns -1 if search_item is not found in array
2020-12-20 16:50:42 -08:00
-1
2020-12-20 16:49:22 -08:00
end
puts(double_linear_search([1, 5, 5, 10], 1))
# => 0
2020-12-20 16:53:04 -08:00
2020-12-20 16:49:22 -08:00
puts(double_linear_search([1, 5, 5, 10], 5))
# => 1
2020-12-20 16:53:04 -08:00
2020-12-20 16:49:22 -08:00
puts(double_linear_search([1, 5, 5, 10], 100))
# => -1
2020-12-20 16:53:04 -08:00
2020-12-20 16:49:22 -08:00
puts(double_linear_search([1, 5, 5, 10], 10))
# => 3