算法实现如下
1 -module(bisearch). 2 -export([start/2]). 3 4 start(Value,List) -> 5 Len = length(List), 6 FirstValue = lists:nth(1, List), 7 LastValue = lists:nth(Len, List), 8 if FirstValue =:= Value orelse LastValue =:= Value -> 9 io:format("found ~w~n", [Value]); % 查找值在列表的首尾 10 true -> 11 Result = calu(1, length(List), Value, List), 12 case Result of 13 found -> io:format("found ~w~n", [Value]); 14 _ -> io:format("not found ~w~n", [Value]) 15 end 16 end. 17 18 %% 二分查找 19 calu(L, H, Value, List) -> 20 M = (L+H) div 2, 21 case L =:= M of 22 true -> none; % 查找范围段只有两个元素,结束查找 23 false -> 24 MValue = lists:nth(M, List), % 计算中值 25 if 26 Value =:= MValue -> 27 found; % 查找成功 28 Value < MValue -> 29 calu(L, M, Value, List); % 设置列表的前段为新的查找范围 30 Value > MValue -> 31 calu(M, H, Value, List) % 设置列表的后段为新的查找范围 32 end 33 end.