Skip to content

Instantly share code, notes, and snippets.

@wang-zhijun
Last active January 20, 2019 09:16
Show Gist options
  • Save wang-zhijun/888e9a0a5cbed5ddc1a3 to your computer and use it in GitHub Desktop.
Save wang-zhijun/888e9a0a5cbed5ddc1a3 to your computer and use it in GitHub Desktop.
ErlangでBinary search インデックスを返す
-module(binary_search).
-export([binary_search/2]).
-include_lib("eunit/include/eunit.hrl").
%% > c(binary_search).
%% 5> binary_search:binary_search([], -1).
%% -1
%% 6> binary_search:binary_search([], 0).
%% -1
%% 7> binary_search:binary_search(lists:seq(3,100000),6 ).
%% 4
%% 8> binary_search:binary_search(lists:seq(3,100000),3 ).
%% 1
%% find `N` in sorted list `List`
binary_search(List, N) ->
binary_search(List, N, 1, length(List), List).
%% _Listは今から処理するリスト
%% _OriListは変わらない、ずっと最初と同じリスト
binary_search(_List, _N, Left, Right, _OriList ) when Left > Right ->
-1;
binary_search(_List, N, Left, Right, OriList ) when Left =< Right ->
Middle = (Left + Right) div 2,
%% OriListを使って、リストの要素を特定している
Item = lists:nth(Middle, OriList),
case Item of
N -> Middle; %% yay, found it!
_ -> case Item > N of
true -> binary_search(lists:sublist(OriList, Middle -1), N, Left, Middle-1, OriList); %% left
false -> binary_search(lists:nthtail(Middle, OriList), N, Middle+1, Right , OriList) %% right
end
end.
@greggy
Copy link

greggy commented Jan 20, 2019

You don't need the first argument in binary_search/5!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment