Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Binary serach in Ruby (#5726)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
  • Loading branch information
3 people committed Jun 24, 2024
1 parent 1d05185 commit 067e8a1
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions program/program/implement-binary-search/ImplementBinarySearch.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 067e8a1

Please sign in to comment.