mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-28 22:24:14 +01:00
Merge pull request #65 from vbrazo/add-recursive-linear-search
Search algorithm: Recursive linear search
This commit is contained in:
commit
6d71f27b2e
2 changed files with 26 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)
|
||||
* [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)
|
||||
|
|
25
searches/recursive_linear_search.rb
Normal file
25
searches/recursive_linear_search.rb
Normal 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
|
Loading…
Reference in a new issue