Last active
August 28, 2022 00:51
-
-
Save visualsayed/5dd11a0933fa2a32b3a161d9532110e0 to your computer and use it in GitHub Desktop.
Implementing binary search in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# recursive implementation of binary search in Ruby | |
def search(arr, val, start_index, end_index) | |
median = (start_index + end_index) / 2 | |
if(arr[median] == val) | |
puts "#{val} is in this list." | |
elsif(start_index >= end_index) | |
puts "#{val} is not in this list." | |
else | |
if(val > arr[median]) | |
search(arr, val, median+1, end_index) | |
else | |
search(arr, val, start_index, median-1) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment