From 4c3bc702f4dc0fc2fb3a5da2bdccdd72b435656a Mon Sep 17 00:00:00 2001 From: Felice Forby Date: Wed, 13 Nov 2019 00:18:34 +0900 Subject: [PATCH] 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 --- .../ruby/02_recursive_binary_search.rb | 26 +++++++++++++++++++ 04_quicksort/ruby/04_recursive_max.rb | 7 ++--- 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 01_introduction_to_algorithms/ruby/02_recursive_binary_search.rb diff --git a/01_introduction_to_algorithms/ruby/02_recursive_binary_search.rb b/01_introduction_to_algorithms/ruby/02_recursive_binary_search.rb new file mode 100644 index 0000000..f2fff1b --- /dev/null +++ b/01_introduction_to_algorithms/ruby/02_recursive_binary_search.rb @@ -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 diff --git a/04_quicksort/ruby/04_recursive_max.rb b/04_quicksort/ruby/04_recursive_max.rb index 59e7d94..fd4f90c 100644 --- a/04_quicksort/ruby/04_recursive_max.rb +++ b/04_quicksort/ruby/04_recursive_max.rb @@ -1,7 +1,8 @@ def max(list) - if list.length == 2 - # condition ? then : else - list[0] > list[1] ? list[0] : list[1] + if list.empty? + nil + elsif list.length == 1 + numbers[0] else sub_max = max(list[1..-1]) list[0] > sub_max ? list[0] : sub_max