From 067e8a1599b8a813dfcf1e21e7ee2475ffd28e6a Mon Sep 17 00:00:00 2001 From: Md Riyazul Islam <121575277+Riyazul555@users.noreply.github.com> Date: Mon, 24 Jun 2024 22:28:20 +0530 Subject: [PATCH] Binary serach in Ruby (#5726) Co-authored-by: Riyazul555 Co-authored-by: Anandha Krishnan S --- .../ImplementBinarySearch.rb | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 program/program/implement-binary-search/ImplementBinarySearch.rb diff --git a/program/program/implement-binary-search/ImplementBinarySearch.rb b/program/program/implement-binary-search/ImplementBinarySearch.rb new file mode 100644 index 000000000..6c459652f --- /dev/null +++ b/program/program/implement-binary-search/ImplementBinarySearch.rb @@ -0,0 +1,29 @@ +def binary_search(arr, x) + lower_bound = 0 + upper_bound = arr.length - 1 + + while lower_bound <= upper_bound + mid_point = lower_bound + (upper_bound - lower_bound) / 2 + + if arr[mid_point] < x + lower_bound = mid_point + 1 + elsif arr[mid_point] > x + upper_bound = mid_point - 1 + else + return mid_point # x found at mid_point + end + end + + return -1 # x does not exist +end + +# Example usage +arr = [2, 3, 4, 10, 40] +x = 10 + +result = binary_search(arr, x) +if result != -1 + puts "Element #{x} is present at index #{result}" +else + puts "Element #{x} is not present in array" +end