-module(my_array).
-export([sum/1, print/1, average/1, reverse/1, indexOf/2, sub/3, max/1, bubble_sort/1, quick_sort/1, insert_sort/1]).
sum([H|T]) -> H + sum(T);
sum([]) -> 0.
print([H|T]) -> io:format("~w~n",[H]),
print(T);
print([]) -> io:format("end~n").
average(L) -> sum(L)/length(L).
reverse([H|T]) -> reverse(T) ++ [H];
reverse([]) -> [].
indexOf(I,[H|T]) when I>0 -> indexOf(I-1,T);
indexOf(0,[H|T]) -> H.
sub(A, B, L) -> indexOf(A, L) ++ sub(A+1, B, L);
sub(B, B, L) -> [].
max([H|T]) -> max(H, T).
max(H, []) -> H;
max(X, [H|T]) when X >= H -> max(X, T);
max(X, [H|T]) when X < H -> max(H, T).
bubble_sort([]) -> [];
bubble_sort(L) ->
X = max(L),
[X] ++ bubble_sort(L -- [X]).
quick_sort([]) -> [];
quick_sort([H|T]) -> quick_sort([X || X <- T, X =< H]) ++ [H] ++ quick_sort([X || X <- T, X > H]).
insert(L, A) -> insert(L, [], A).
insert([H|T], Less, A) ->
if
H < A -> insert(T, Less ++ [H], A);
H >= A -> Less ++ [A] ++ [H] ++ T
end;
insert([], Less, A) -> reverse([A] ++ reverse(Less)).
insert_sort([H|T]) -> insert_sort([H], T).
insert_sort(L, []) -> L;
insert_sort(L1, [H|T]) -> insert_sort(insert(L1, H), T).
Erlang的一些练习代码(数组排序相关)
最新推荐文章于 2022-06-23 23:54:15 发布