Skip to content

Instantly share code, notes, and snippets.

@leopolicastro
Created March 11, 2022 16:52
Show Gist options
  • Save leopolicastro/6fe38ab7925d8ec2c4ddf91fe53a65b6 to your computer and use it in GitHub Desktop.
Save leopolicastro/6fe38ab7925d8ec2c4ddf91fe53a65b6 to your computer and use it in GitHub Desktop.
def binary_search(ordered_array, search_value)
lower_bound = 0
upper_bound = ordered_array.length - 1
while lower_bound <= upper_bound do
midpoint = (lower_bound + upper_bound) / 2
value_at_midpoint = ordered_array[midpoint]
if search_value == value_at_midpoint
return midpoint
elsif search_value < value_at_midpoint
upper_bound = midpoint - 1
elsif search_value > value_at_midpoint
lower_bound = midpoint + 1
end
end
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment