Skip to content

Instantly share code, notes, and snippets.

@rodjek
Created May 2, 2010 13:48
Show Gist options
  • Save rodjek/387128 to your computer and use it in GitHub Desktop.
Save rodjek/387128 to your computer and use it in GitHub Desktop.
-module(bsearch).
-export([find/2]).
find(List, Value_to_find) ->
Max = lists:max(List),
Min = lists:nth(1, List),
case Value_to_find of
_ when Value_to_find > Max -> {error, toobig};
_ when Value_to_find < Min -> {error, toosmall};
_ -> {ok, find(List, Value_to_find, 0)}
end.
find(List, Value_to_find, Offset) ->
End_i = length(List),
Mid_i = floor(End_i/2),
Mid_e = lists:nth(Mid_i, List),
case Mid_e of
_ when Value_to_find > Mid_e ->
{_, Last} = lists:split(Mid_i, List),
find(Last, Value_to_find, (Offset + Mid_i));
_ when Value_to_find < Mid_e ->
{First, _} = lists:split(Mid_i, List),
find(First, Value_to_find, Offset);
_ -> (Mid_i + Offset)
end.
floor(X) ->
T = erlang:trunc(X),
case (X - T) of
Neg when Neg < 0 -> T - 1;
Pos when Pos > 0 -> T;
_ -> T
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment