Binary_search.rb

This content was produced by an LLM and could include errors.

This script defines the binary_search function. It efficiently finds the index of a target element within a pre-sorted array using the standard binary search algorithm.

# frozen_string_literal: true
#=> nil

def binary_search(data, target)
  min_index = 0
  max_index = data.length - 1
  
  while min_index <= max_index
    mid_index = min_index + (max_index - min_index) / 2
    standard = data[mid_index]
    
    if standard == target
      return mid_index
      elsif standard < target
      min_index = mid_index + 1
      else
      max_index = mid_index - 1
    end
  end
  -1
end
#=> :binary_search

data = [0, 1, 34, 56, 78]
#=> [0, 1, 34, 56, 78]
data.sort!
#=> [0, 1, 34, 56, 78]
p binary_search(data, 34)
2
#=> 2

cities = %w[fukuoka hiroshima kobe kyoto nagoya osaka sapporo tokyo yokohama]
#=> ["fukuoka",
#...
p binary_search(cities, "sapporo")
6
#=> 6

Ruby 4.0.3