简体   繁体   中英

How to sort a list in ascending or descending order?

Is there a way to sort all the elements of a list in ascending or descending order?

> List1 = [4,3,2,6,1,5].
> sort(List1) == [1,2,3,4,5,6]
> true
lists:sort([2,3,6,5,1,7,13,4]).

or

lists:sort(ListToSort).

will return a sorted list of integers in an ascending order. Thanks to @Dogbert for pointing out the obvious.

We have a lot of way to sort, so sometime you can do that for yourself. It's the way I learnt Erlang :)

-spec sort(List) -> SortedList when
  List :: [integer()],
  SortedList :: [integer()].
sort([Pivot | Tail]) ->
{Smaller, Larger} = partition(Pivot, Tail, [], []),
sort(Smaller) ++ [Pivot] ++ sort(Larger);
sort([]) -> [].

partition(Check, [Head | Tail], Smaller, Larger) ->
    case Head =< Check of
        true -> partition(Check, Tail, [Head | Smaller], Larger);
        false -> partition(Check, Tail, Smaller, [Head | Larger])
    end;
partition(_, [], Smaller, Larger) -> {Smaller, Larger}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM