使用Erlang实现简单的排序算法:快速排序,冒泡排序,插入排序

-module(sort).

-compile(export_all).


%%快速排序
qsort([]) -> [];  
qsort([Pivot|T]) ->  
    qsort([X || X <- T,X < Pivot])  
    ++ [Pivot] ++  
        qsort([X || X <-T,X >= Pivot]). 


%%冒泡排序
bubble_sort(L) -> bubble_sort(L,len(L)).  
bubble_sort(L,1) -> L;  
bubble_sort([H|T],N) ->   
    Result = bubble_once(H,T),  
    io:format("Result is  ~p~n",[Result]),  
    bubble_sort(Result,N-1).


bubble_once(H,[]) -> [H];  
bubble_once(X,[H|T]) ->  
    if X > H ->  
            [H|bubble_once(X,T)];  
        true ->  
            [X|bubble_once(H,T)]  
    end.  
  
len([]) -> 0;  
len([_H|T]) -> 1 + len(T).


%%插入排序
insert_sort(L) -> insert_sort([],L).  
insert_sort(L,[]) -> L;  
insert_sort(L,[H|T]) ->  
    insert_sort(normal(H,L),T).  
  
normal(X,[]) -> [X];  
normal(X,[H|T]) ->  
    if X > H ->  
            [H|normal(X,T)];  
        true ->  
            [X|[H|T]]  
    end.

猜你喜欢

转载自www.cnblogs.com/unqiang/p/9203391.html