Created
August 22, 2012 21:33
-
-
Save jadeallenx/3429596 to your computer and use it in GitHub Desktop.
binary search in erlang
This file contains hidden or 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
-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