Sort stability: Difference between revisions
Content added Content deleted
(→{{header|TXR}}: New section.) |
|||
Line 947: | Line 947: | ||
p ary.stable_sort_by {|x| x[1]} |
p ary.stable_sort_by {|x| x[1]} |
||
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</lang> |
# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]</lang> |
||
=={{header|Rust}}== |
|||
Rust's builtin sorts (.sort(), .sort_by(...), .sort_by_key(...)) are all stable |
|||
<lang rust>fn main() { |
|||
let country_city = vec![("UK", "London"), |
|||
("US", "New York"), |
|||
("US", "Birmingham"), |
|||
("UK", "Birmingham")]; |
|||
let mut city_sorted = country_city.clone(); |
|||
city_sorted.sort_by_key(|k| k.1); |
|||
let mut country_sorted = country_city.clone(); |
|||
country_sorted.sort_by_key(|k| k.0); |
|||
println!("Original:"); |
|||
for x in &country_city { |
|||
println!("{} {}", x.0, x.1); |
|||
} |
|||
println!("\nWhen sorted by city:"); |
|||
for x in &city_sorted { |
|||
println!("{} {}", x.0, x.1); |
|||
} |
|||
println!("\nWhen sorted by county:"); |
|||
for x in &country_sorted { |
|||
println!("{} {}", x.0, x.1); |
|||
} |
|||
}</lang> |
|||
Output: <pre>Original: |
|||
UK London |
|||
US New York |
|||
US Birmingham |
|||
UK Birmingham |
|||
When sorted by city: |
|||
US Birmingham |
|||
UK Birmingham |
|||
UK London |
|||
US New York |
|||
When sorted by county: |
|||
UK London |
|||
UK Birmingham |
|||
US New York |
|||
US Birmingham</pre> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |