Anonymous user
Sort stability: Difference between revisions
Added Elixir
(Nimrod -> Nim) |
(Added Elixir) |
||
Line 137:
=={{header|Déjà Vu}}==
The included sorting algorithm, <code>sort</code>, is stable.
=={{header|Elixir}}==
Enum.sort and Enum.sort_by of Elixir are stable.
These functions use merge sort algorithm.
The sorting algorithm will be stable as long as the given function returns true for values considered equal:
<lang elixir>cities = [ {"UK", "London"},
{"US", "New York"},
{"US", "Birmingham"},
{"UK", "Birmingham"} ]
IO.inspect Enum.sort(cities)
IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end)
IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end)
IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end)</lang>
{{out}}
<pre>
[{"UK", "Birmingham"}, {"UK", "London"}, {"US", "Birmingham"}, {"US", "New York"}]
[{"US", "New York"}, {"US", "Birmingham"}, {"UK", "London"}, {"UK", "Birmingham"}]
[{"UK", "London"}, {"UK", "Birmingham"}, {"US", "New York"}, {"US", "Birmingham"}]
[{"US", "Birmingham"}, {"UK", "Birmingham"}, {"UK", "London"}, {"US", "New York"}]
</pre>
'''Note:''' If the function does not return true, the sorting is not stable and the order of equal terms may be shuffled:
<lang elixir>IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) > elem(b,0) end)</lang>
{{out}}
<pre>
[{"US", "Birmingham"}, {"US", "New York"}, {"UK", "Birmingham"}, {"UK", "London"}]
</pre>
=={{header|Erlang}}==
|