Heap (Erlang)
From LiteratePrograms
Heap structure in Erlang
-module(heap).
-export([start/0]).
start() ->
L=[7,1,3,4,0,5,5,8],
heapify(L).
heapify(L)->
heapify(L, []).
heapify([], Acc) ->
Acc;
heapify([H|T], Acc)->
K=Acc ++ [H],
J=siftup(K),
heapify(T, J).
siftup(M)->
siftup(M, length(M)).
siftup(M, N) when N > 0->
Ppos=trunc((N+1)/2),
P=lists:nth(Ppos, M),
Q=lists:nth(N, M),
case N > 0 andalso Q > P of
true ->
{J, [_|Ta]}=lists:split(Ppos-1, M),
Lx=J++[Q]++Ta,
{K, [_|Tb]}=lists:split(N-1, Lx),
Ly=K ++ [P] ++ Tb,
siftup(Ly, Ppos);
false ->
M
end;
siftup(M, _) ->
M.
| Download code |