Sort stability: Difference between revisions

Content added Content deleted
(→‎{{header|Ruby}}: documenting difficulties)
m (→‎{{header|Ruby}}: link to stable merge sort)
Line 57: Line 57:
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</lang>
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</lang>


So, if we want to use Ruby's <code>sort</code> ''and'' we want stability, we might be better off using a custom Schwartzian transform:
So, if we want to use Ruby's <code>sort</code> ''and'' we want stability, we might be better off using [[Merge sort]] or a Schwartzian transform:
<lang ruby>
<lang ruby>ary.each_index \
ary.each_index \
.map {|i| ary[i] + [i]} \
.map {|i| ary[i] + [i]} \
.sort {|a,b| (a[1] <=> b[1]).nonzero? or a[-1] <=> b[-1]} \
.sort {|a,b| (a[1] <=> b[1]).nonzero? or a[-1] <=> b[-1]} \