Initial Commit
This commit is contained in:
25
binary.exs
Normal file
25
binary.exs
Normal file
@@ -0,0 +1,25 @@
|
||||
defmodule BinarySearch do
|
||||
def binary_search(_numbers, _key, low, high) when low > high do
|
||||
:not_found
|
||||
end
|
||||
|
||||
@spec binary_search(list, integer, integer, integer) :: integer | :not_found
|
||||
def binary_search(numbers, key, low, high) do
|
||||
md = low + Integer.floor_div(high-low, 2)
|
||||
IO.inspect(md)
|
||||
case elem(numbers, md) do
|
||||
x when x > key -> binary_search(numbers, key, low, md-1)
|
||||
x when x < key -> binary_search(numbers, key, md+1, high)
|
||||
x when x == key -> md
|
||||
end
|
||||
end
|
||||
|
||||
@spec search(tuple, integer) :: {:ok, integer} | :not_found
|
||||
def search(numbers, key) do
|
||||
case binary_search(numbers, key, 0, tuple_size(numbers)-1) do
|
||||
:not_found -> :not_found
|
||||
x -> {:ok, x}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user