Last active
October 22, 2016 17:05
-
-
Save xiaohanyu/e64111caec52709237ee8633b3f54085 to your computer and use it in GitHub Desktop.
A binary search demo in Elixir(from "Programming Elixir" book, Chapter 6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Chop do | |
def guess(final, range) do | |
low..high = range | |
middle = div(low + high, 2) | |
_guess_helper(final, low, high, middle) | |
end | |
defp _guess_helper(final, _low, _high, middle) when final === middle do | |
middle | |
end | |
defp _guess_helper(final, low, _high, middle) when final < middle do | |
IO.puts "Is it #{middle}" | |
_guess_helper(final, low, middle, div(low + middle, 2)) | |
end | |
defp _guess_helper(final, _low, high, middle) when final > middle do | |
IO.puts "Is it #{middle}" | |
_guess_helper(final, middle, high, div(middle + high, 2)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment