mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-28 22:24:14 +01:00
Merge pull request #67 from vbrazo/add-double-linear-search
Search algorithm: Double linear search
This commit is contained in:
commit
e83b26df83
2 changed files with 30 additions and 0 deletions
|
@ -47,6 +47,7 @@
|
|||
* [Binary Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/binary_search.rb)
|
||||
* [Depth First Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/depth_first_search.rb)
|
||||
* [Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/linear_search.rb)
|
||||
* [Double Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/double_linear_search.rb)
|
||||
* [Recursive Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/recursive_linear_search.rb)
|
||||
|
||||
## Sorting
|
||||
|
|
29
searches/double_linear_search.rb
Normal file
29
searches/double_linear_search.rb
Normal file
|
@ -0,0 +1,29 @@
|
|||
# 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
|
||||
return start_ind if array[start_ind] == search_item
|
||||
return end_ind if array[end_ind] == search_item
|
||||
|
||||
start_ind += 1
|
||||
end_ind -= 1
|
||||
end
|
||||
|
||||
# returns -1 if search_item is not found in array
|
||||
-1
|
||||
end
|
||||
|
||||
puts(double_linear_search([1, 5, 5, 10], 1))
|
||||
# => 0
|
||||
|
||||
puts(double_linear_search([1, 5, 5, 10], 5))
|
||||
# => 1
|
||||
|
||||
puts(double_linear_search([1, 5, 5, 10], 100))
|
||||
# => -1
|
||||
|
||||
puts(double_linear_search([1, 5, 5, 10], 10))
|
||||
# => 3
|
Loading…
Reference in a new issue