erlang算法:插入、归并、快速、二分查找

本人现在大二,在看《Erlang程序设计》,结合正在学习的《算法导论》,写了几个算法,运行起来效率可能不是很高,大神们有好的思路也可以提提,小弟不胜感激!

总体来说,我觉得快速排序效率最高。

 

插入排序:一开始合并列表是用 | 的,试验几次后老出现[List,[]],吓尿了,修改几次后无果,只能退而使用效率低的++

-module(sort_cr).
-compile(export_all).

sort([]) -> [];
sort([H|T]) -> sort([H],T,[]).

sort(A,[],[]) -> A;
sort(A,[],B) -> B++A;
sort([],[B1|B2],N) -> sort(N++[B1],B2,[]);
sort([A1|A2],[B1|B2],N) ->
    if
        A1<B1  -> sort(A2,[B1|B2],N++[A1]);
        A1>=B1 -> sort ([B1,A1|A2],B2,N)
    end.

 

归并排序:发现了一个强悍的内置函数lists:split(N,List),在第N位把列表拆成两部分,仿着sudayly大神的思路写了一个

-module(sort_gb).
-compile(export_all).

sort([]) -> [];
sort([A]) -> [A];
sort(L) ->
    {L1,L2} = lists:split(length(L) div 2,L),
    sort(sort(L1),sort(L2)).

sort([],L) -> L;
sort(L,[]) -> L;
sort([H1|T1],[H2|T2]) ->
    if
        H1 =< H2 -> [H1|sort(T1,[H2|T2])];
        H1 >  H2 -> [H2|sort([H1|T1],T2)]
    end.

 

快速排序:自己写着最有感觉的算法

-module(sort_ks).
-export([up/1,down/1]).

up([]) -> [];
up([H|R]) ->
    up([X||X<-R,X<H])
    ++[H]++
    up([X||X<-R,X>=H]).

down([]) -> [];
down([Key|T]) ->
    down([X||X<-T,X>=Key])
    ++[Key]++
    down([X||X<-T,X<Key]).

 

二分查找:还是用了强大的内置函数lists:nth(N,List),取列表List中第N个值,类似C的数组array[i],仿着莊博堯大神的思路写的

-module(bin_search).
-compile(export_all).
-import(lists,[sort/1,nth/2]).

search(_Find,[]) ->
    io:format("list is empty!~n");
search(Find,List) ->
    Sort=sort(List),
    Num=length(List),
    match(Find,1,Num,Sort).

match(Find,First,Last,Sort) when First=<Last ->
    Mid=((Last-First) div 2)+First,
    Key=nth(Mid,Sort),
    if
        Find==Key -> 
            io:format("~w is No.~w in ~w~n",[Find,Mid,Sort]);
        Find>Key -> match(Find,Mid+1,Last,Sort);
        Find<Key -> match(Find,First,Mid-1,Sort)
    end;
match(_Find,First,Last,_Sort) when First>Last ->
    io:format("not found!~n").

 

堆排序:完全没有思路,求大神指点~

 

转载于:https://www.cnblogs.com/xiaopengge/archive/2013/04/09/3009452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值