Ruby Program to Implement Binary Search

Ruby Program to Implement Binary Search

Searching efficiently is a key skill in programming, especially when working with large datasets. One of the most popular and efficient searching techniques is Binary Search. Unlike Linear Search, which checks each element one by one, Binary Search works on sorted arrays and repeatedly divides the array in half to locate the target element. This makes Binary Search much faster for large datasets and a fundamental algorithm for any programmer to understand.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary Search is widely used in real-world applications, such as searching in databases, finding values in sorted lists, or even in certain game algorithms where efficiency is critical. Learning Binary Search in Ruby not only helps beginners understand the power of divide-and-conquer strategies but also provides a foundation for more advanced searching and sorting algorithms. In this article, we will explore multiple ways to implement Binary Search in Ruby, including iterative and recursive approaches, so beginners can see the versatility of this algorithm in practice.

Program 1: Iterative Binary Search

This program demonstrates Binary Search using an iterative approach to find a target number in a sorted array.

# Program 1: Iterative Binary Search
def binary_search_iterative(array, target)

  left = 0
  right = array.length - 1

  while left <= right

    mid = (left + right) / 2

    if array[mid] == target
      return mid
    elsif array[mid] < target
      left = mid + 1
    else
      right = mid - 1
    end

  end

  -1

end

numbers = [2, 5, 8, 12, 16, 23, 38, 45, 56]
target = 23
index = binary_search_iterative(numbers, target)

if index != -1
  puts "Element #{target} found at index #{index}"
else
  puts "Element #{target} not found"
end

In this iterative approach, we repeatedly calculate the middle index of the current search range. Depending on whether the target is smaller or larger than the middle value, we adjust the search boundaries. Beginners can see how dividing the search space drastically reduces the number of comparisons compared to Linear Search.

Program 2: Recursive Binary Search

Binary Search can also be implemented recursively. This approach emphasizes the divide-and-conquer strategy in a natural way.

# Program 2: Recursive Binary Search
def binary_search_recursive(array, target, left = 0, right = nil)

  right = array.length - 1 if right.nil?
  return -1 if left > right

  mid = (left + right) / 2

  return mid if array[mid] == target

  if array[mid] < target
    binary_search_recursive(array, target, mid + 1, right)
  else
    binary_search_recursive(array, target, left, mid - 1)
  end

end

numbers = [1, 3, 5, 7, 9, 11, 13, 15]
target = 9
index = binary_search_recursive(numbers, target)

if index != -1
  puts "Element #{target} found at index #{index} (recursive)"
else
  puts "Element #{target} not found (recursive)"
end

Here, the function calls itself with a reduced search range based on the comparison with the middle element. Beginners can see how recursion mirrors the process of dividing the array in half until the target is found or the range becomes empty.

Program 3: Binary Search on Floating-Point Numbers

Binary Search is not limited to integers; it can also be applied to floating-point numbers as long as the array is sorted.

# Program 3: Binary Search for floating-point numbers
def binary_search_iterative(array, target)

  left = 0
  right = array.length - 1

  while left <= right

    mid = (left + right) / 2

    if array[mid] == target
      return mid
    elsif array[mid] < target
      left = mid + 1
    else
      right = mid - 1
    end

  end

  -1

end

numbers = [0.5, 1.2, 2.8, 3.6, 4.1, 5.9]
target = 3.6

index = binary_search_iterative(numbers, target)

if index != -1
  puts "Floating-point element #{target} found at index #{index}"
else
  puts "Floating-point element #{target} not found"
end

Since Binary Search relies on comparisons rather than arithmetic, it works naturally with floats. Beginners can see the flexibility of the algorithm across different numeric types.

Program 4: Binary Search to Find First Occurrence in Duplicates

Binary Search can also be modified to handle arrays with duplicate elements and find the first occurrence of the target.

# Program 4: Binary Search for first occurrence
def binary_search_first(array, target)

  left = 0
  right = array.length - 1
  result = -1

  while left <= right

    mid = (left + right) / 2

    if array[mid] == target

      result = mid
      right = mid - 1  # Continue searching to the left

    elsif array[mid] < target
      left = mid + 1
    else
      right = mid - 1
    end

  end

  result

end

numbers = [1, 2, 4, 4, 4, 5, 6]
target = 4
index = binary_search_first(numbers, target)

if index != -1
  puts "First occurrence of element #{target} is at index #{index}"
else
  puts "Element #{target} not found"
end

This approach slightly modifies the standard Binary Search by continuing the search to the left whenever the target is found. Beginners can understand that small changes in logic allow Binary Search to solve more specialized problems.

Frequently Asked Questions (FAQ)

Here are some common questions beginners often have about Binary Search:

Q1: What is the time complexity of Binary Search?
Binary Search has a time complexity of O(log n), making it very efficient for large datasets compared to Linear Search.

Q2: Can Binary Search work on unsorted arrays?
No, the array must be sorted for Binary Search to function correctly.

Q3: Is Binary Search better than Linear Search?
For large, sorted datasets, Binary Search is much faster. Linear Search may still be preferred for small or unsorted arrays.

Q4: Can Binary Search handle duplicate elements?
Yes, with small modifications, Binary Search can find the first, last, or any occurrence of duplicate elements.

Q5: Can Binary Search be used on strings or other data types?
Yes, as long as the data supports comparison operators (<, >, ==), Binary Search can be applied.

Conclusion

In this article, we explored multiple ways to implement Binary Search in Ruby, including iterative and recursive methods, handling floating-point numbers, and finding the first occurrence in arrays with duplicates. Binary Search is an efficient, versatile, and foundational algorithm that every beginner should learn. By practicing these examples, beginners will understand how to divide search spaces, use recursion effectively, and solve real-world problems with fast searching techniques. Mastering Binary Search lays a strong foundation for learning more advanced algorithms and working with larger datasets efficiently.

Scroll to Top