Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,401 questions

56,365 answers

573 users

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 May 8 by avibootz
...