How to implement the binary search algorithm in Ruby

1 Answer

0 votes
# Performs binary search on a sorted array.
# Returns the index of the target value, or nil if not found.
def binary_search(array, target)
  left  = 0
  right = array.length - 1

  while left <= right
    mid = (left + right) / 2
    value = array[mid]

    if value == target
      return mid
    elsif value < target
      left = mid + 1
    else
      right = mid - 1
    end
  end

  nil  # Not found
end

# Example usage
arr = [3, 4, 8, 9, 10, 17, 21, 28, 33, 36, 42]
puts binary_search(arr, 21)   # => 6
puts binary_search(arr, 2)   # => nil



# run
# 
# 6
#
#

 



answered 5 days ago by avibootz
...