Reputation: 1031
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
Upvotes: 1
Views: 3782
Reputation: 1369
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}.
Upvotes: 3
Reputation: 1031
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.
Upvotes: 5