Search code examples
erlangbubble-sort

Erlang Bubble sort


I'm learning Erlang and decided to implement bubble sort in it, it took me some effort and in result i've succeded, but i see that my way of thinking is incorrect, is there more effecient way to implement it or not?

bubble_sort(L) ->
if 
length(L) > 1 ->
    SL=bubble_sort_p(L),
    bubble_sort(lists:sublist(SL,1,length(SL)-1)) ++ [lists:last(SL)];
true -> L
end.

bubble_sort_p([]) -> [];    
bubble_sort_p([F | R]) ->
    case length(R) > 0 of
        true -> case F > hd(R) of
                true ->  [hd(R)] ++ bubble_sort_p([F|tl(R)]);
                false -> [F] ++ bubble_sort_p([hd(R)|tl(R)])
            end;
        false -> [F]
    end.

Solution

  • Allow me to re-write your code in a much more readable fashion (without changing anything about the semantics):

    bubble_sort(L) when length(L) =< 1 ->
        L;
    bubble_sort(L) ->
        SL = bubble_sort_p(L),
        bubble_sort(lists:sublist(SL,1,length(SL)-1)) ++ [lists:last(SL)].
    
    bubble_sort_p([])  ->
        [];
    bubble_sort_p([F]) ->
        [F];
    bubble_sort_p([F,G|T]) when F > G ->
        [G|bubble_sort_p([F|T])];
    bubble_sort_p([F,G|T]) ->
        [F|bubble_sort_p([G|T])].
    

    This should allow for much easier contemplation of the things actually going on in the program.