Home
Search
Rust sort Strings Example (Ordering)Sort strings with the sort by function. Use a function that returns Ordering to sort by two properties.
Sort. Sorting a vector of Strings in Rust can be done with a single function call. But more complex sorting, like with 2 properties at once, requires a custom function.
By returning Ordering, we can use a custom function with the sort_by and sort_unstable_by functions. In this way we can implement more complex, compound sorting routines.
An example. To begin, we need to add a "use" statement at the top of the program for "cmp" to access Ordering. In main, we add 5 Strings to a vector.
Tip In main, we call to_string() to get Strings, not str references. With String, we can avoid ownership issues and Rust programs are simpler.
String Array
Sort by The sort_by and sort_unstable_by functions can be used. The unstable version is faster, but may move equal elements more.
Compare The first function is compare_len_reverse_alpha. This has 2 calls to cmp() in it.
Info In "compare" we test the lengths of the 2 string arguments first. If the lengths are equal, we sort them in reverse alphabetical order.
Rust program that sorts Strings with Ordering
use std::cmp::*; fn compare_len_reverse_alpha(a: &String, b: &String) -> Ordering { // Sort by length from short to long first. let length_test = a.len().cmp(&b.len()); if length_test == Ordering::Equal { // If same length, sort in reverse alphabetical order. return b.cmp(&a); } return length_test; } fn main() { // The vec we want to sort. let mut animals = vec![]; animals.push("bird".to_string()); animals.push("elephant".to_string()); animals.push("cat".to_string()); animals.push("ant".to_string()); animals.push("bat".to_string()); // Call the function that returns Ordering. animals.sort_unstable_by(compare_len_reverse_alpha); // Print results. println!("{:?}", animals); }
["cat", "bat", "ant", "bird", "elephant"]
A discussion. In many Rust programs, using the "unstable" functions is acceptable, as the order of equal elements does not matter. There is a performance benefit to "unstable" too.
Also For reverse sorts, just change the order of the comparisons (when calling the cmp function).
A summary. We implemented a compound sort on a string vector in Rust. Often we need to sort by one aspect, and then by another—a custom Ordering function is needed for this.
Sort HashMap
Home
© 2007-2022 sam allen.
see site info on the changelog.