Merge pull request #65 from vbrazo/add-recursive-linear-search

Search algorithm: Recursive linear search
This commit is contained in:
Vitor Oliveira 2020-12-28 14:37:32 -08:00 committed by GitHub
commit 6d71f27b2e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 0 deletions

View file

@ -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)
* [Recursive Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/recursive_linear_search.rb)
## Sorting
* [Bogo Sort](https://github.com/TheAlgorithms/Ruby/blob/master/sorting/bogo_sort.rb)

View file

@ -0,0 +1,25 @@
# A pure Ruby implementation of a recursive linear search algorithm
def rec_linear_search(sequence, low, high, target)
raise Exception('Invalid upper or lower bound!') unless high < sequence.length && low < sequence.length
return -1 if high < low
return low if sequence[low] == target
return high if sequence[high] == target
rec_linear_search(sequence, low + 1, high - 1, target)
end
puts(rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0))
# => 0
puts(rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700))
# => 4
puts(rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30))
# => 1
puts(rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6))
# => -1