Skip to content

Instantly share code, notes, and snippets.

@jadeallenx
Created August 22, 2012 21:33
Show Gist options
  • Save jadeallenx/3429596 to your computer and use it in GitHub Desktop.
Save jadeallenx/3429596 to your computer and use it in GitHub Desktop.
binary search in erlang
-module(t).
-export([chop/2]).
chop(Key, List) ->
chop(Key, List, 0).
chop(Key, List, Acc) ->
Mid = length(List) div 2,
{List1, List2} = lists:split(Mid, List),
%io:format("List1> ~p~nList2> ~p~n Mid> ~p~n Acc> ~p~n", [List1, List2, Mid, Acc]),
case hd(List2) of
Item when Key /= Item andalso List1 =:= [] ->
erlang:error(notfound);
Item when Key < Item ->
chop(Key, List1, Acc);
Item when Key > Item ->
chop(Key, List2, Acc + Mid);
Item when Key == Item ->
Acc+Mid+1
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment