Add recursive binary search for ruby (ch. 1) and improve recursive max for ruby (ch. 4) (#113)

* add recursive binary search for ruby

* account for cases with empty lists and lists with only one item

* use p instead of print to show nil value

* add newline at end of file
This commit is contained in:
Felice Forby
2019-11-13 00:18:34 +09:00
committed by Aditya Bhargava
parent 6b9faa9cab
commit 4c3bc702f4
2 changed files with 30 additions and 3 deletions

View File

@@ -0,0 +1,26 @@
def binary_search(list, item, low = 0, high = list.length - 1)
while low <= high
mid = (low + high) / 2
guess = list[mid]
if guess == item
return mid
elsif guess > item
high = mid - 1
binary_search(list, item, low, high)
else
low = mid + 1
binary_search(list, item, low, high)
end
end
# If item is not found
return nil
end
# Create array with numbers 1 through 100
my_list = (1..100).to_a
puts binary_search(my_list, 2) # => 1
puts binary_search(my_list, 50) # => 49
p binary_search(my_list, 101) # => nil