zoukankan      html  css  js  c++  java
  • 用Erlang实现冒泡排序算法

     直接上代码

     1 -module(bubblesort).
     2 -export([start/1]).
     3 
     4 start(List) ->
     5     SortedList = sort(List, []),
     6     io:format("SortedList:~w~n", [SortedList]).
     7 
     8 %% 冒泡算法:每次step得到一个最大值,对余下的列表再进行递归调用
     9 sort([], SortedList) ->
    10     SortedList;
    11 sort(List, SortedList) ->
    12     {Max, T} = step(List),
    13     sort(T, [Max] ++ SortedList).
    14 
    15 %% 将列表的第一个元素作为最大值与列表中的其它元素进行比较
    16 step([H|T]) ->
    17     step(H, T, []).
    18 
    19 %% 得到最大值
    20 step(Max, [], T1) ->
    21     {Max, T1};
    22 step(Max, [H|T], T1) ->
    23     if 
    24         Max >= H -> step(Max, T, [H] ++ T1);
    25         Max < H -> step(H, T, [Max] ++ T1)
    26     end.

     附注:

    在网上看见一段计算九九乘法表的代码,摘录如下

    1 foo() -> foo(1,1).
    2 foo(9,9) -> io:format("~p*~p=~p \n",[9,9,9*9]);
    3 foo(X,X) -> io:format("~p*~p=~p \n",[X,X,X*X]),foo(1,X+1);
    4 foo(X,Y) -> io:format("~p*~p=~p    ",[X,Y,X*Y]),foo(X+1,Y).

    我称之为回车换行算法,精妙之处在于第3行foo(1,X+1),1表示回车,第一个乘法因子从1开始计算,X+1表示换行,第二个乘法因子递加1

    上善若水
  • 相关阅读:
    mybatis-cache model
    多线程开发(1)
    正则表达式(3) — 正则表达式库
    正则表达式(2) — 表达式规则
    我在迈瑞工作的两年总结
    正则表达式(1) — 常用的表达式
    C++系列(2) — 智能指针
    C++系列(1) — string
    路径去除前缀
    SIMD性能优化
  • 原文地址:https://www.cnblogs.com/netbuddy/p/2815012.html
Copyright © 2011-2022 走看看