String Sort List

From Erlang Community

(Difference between revisions)
Revision as of 22:14, 18 August 2006 (edit)
Cyberlync (Talk | contribs)

← Previous diff
Current revision (12:54, 23 November 2006) (edit) (undo)
Gordon guthrie (Talk | contribs)
(Solution)
 
(3 intermediate revisions not shown.)
Line 21: Line 21:
The sort operation uses the merge-sort algorithm, which takes time O(n log n) where n is the length of the list. The sort operation uses the merge-sort algorithm, which takes time O(n log n) where n is the length of the list.
-[[Category:CookBook]]+[[Category:CookBook]][[Category:StringRecipes]][[Category:ListRecipes]]

Current revision

Sorting a list of strings

[edit] Problem

You want to sort a list of strings.

[edit] Solution

Use the lists:sort operation to sort the lists. Note that by default sorting is case-sensitive. However, since you can use the lists:sort/2 variant of the function to supply your own sorting function this can be modified.

1> lists:sort(["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
2> lists:sort(fun(A, B) -> A =< B end, ["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
3> lists:sort(fun(A, B) -> A =< B end, ["foo", "bar", "baz", "qux"]).
["bar","baz","foo","qux"]
4> lists:sort(fun(A, B) -> A >= B end, ["foo", "bar", "baz", "qux"]).
["qux","foo","baz","bar"]

The sort operation uses the merge-sort algorithm, which takes time O(n log n) where n is the length of the list.

Erlang/OTP Projects
Personal tools