Skip to content

Commit d41f39a

Browse files
author
José Valim
committed
Add a note about Enum.sort/2 stability, closes #2163
1 parent 44c81ae commit d41f39a

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

lib/elixir/lib/enum.ex

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,12 +1473,14 @@ defmodule Enum do
14731473
end
14741474

14751475
@doc """
1476-
Returns a sorted list of collection elements. Uses the merge sort algorithm.
1476+
Sorts the collection according to Elixir's term ordering.
1477+
1478+
Uses the merge sort algorithm.
14771479
14781480
## Examples
14791481
14801482
iex> Enum.sort([3, 2, 1])
1481-
[1,2,3]
1483+
[1, 2, 3]
14821484
14831485
"""
14841486
@spec sort(t) :: list
@@ -1491,14 +1493,27 @@ defmodule Enum do
14911493
end
14921494

14931495
@doc """
1494-
Returns a list of collection elements sorted by the given function.
1496+
Sorts the collection by the given function.
14951497
1496-
Uses the merge sort algorithm.
1498+
This function uses the merge sort algorithm. The given function
1499+
must return false if the first argument is less than right one.
14971500
14981501
## Examples
14991502
15001503
iex> Enum.sort([1, 2, 3], &(&1 > &2))
1501-
[3,2,1]
1504+
[3, 2, 1]
1505+
1506+
The sorting algorithm will be stable as long as the given function
1507+
returns true for values considered equal:
1508+
1509+
iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) <= byte_size(&2))
1510+
["of", "some", "kind", "monster"]
1511+
1512+
If the function does not return true, the sorting is not stable and
1513+
the order of equal terms may be shuffled:
1514+
1515+
iex> Enum.sort ["some", "kind", "of", "monster"], &(byte_size(&1) < byte_size(&2))
1516+
["of", "kind", "some", "monster"]
15021517
15031518
"""
15041519
@spec sort(t, (element, element -> boolean)) :: list

0 commit comments

Comments
 (0)