Skip to content

Commit 8ed03e7

Browse files
spadarjauhienegonSchiele
authored andcommitted
Add Elixir example for binary search
1 parent bb4a863 commit 8ed03e7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
defmodule BinarySearch do
2+
def search(list, item) do
3+
low = 0
4+
high = length(list) - 1
5+
6+
do_search(list, item, low, high)
7+
end
8+
9+
defp do_search(_, _, low, high) when high < low, do: nil
10+
11+
defp do_search(list, item, low, high) do
12+
mid = div(low + high, 2)
13+
guess = Enum.at(list, mid)
14+
15+
cond do
16+
guess == item -> mid
17+
guess > item -> do_search(list, item, low, mid - 1)
18+
true -> do_search(list, item, mid + 1, high)
19+
end
20+
end
21+
end
22+
23+
my_list = [1, 3, 5, 7, 9]
24+
25+
IO.puts(BinarySearch.search(my_list, 3))
26+
# => 1
27+
28+
IO.inspect(BinarySearch.search(my_list, -1))
29+
# => nil

0 commit comments

Comments
 (0)