In Rust, a vector refers to a dynamic, growable array type that is used to store the elements of the same type. The vector data type is provided in the Rust standard library and imports a wide range of traits and properties.
One of the most common vector operations in Rust is sorting. Sorting a vector is a fundamental task in many programming languages and applies to many areas such as data processing, numerical analysis, and algorithms.
Rust provides a rich set of functions and methods to sort the vectors efficiently and effectively. In this tutorial, we will explore the different ways to sort the vectors in Rust.
Define a Vector
To create a vector in Rust, we can use the Vec method as demonstrated in the following example:
In the provided example, we define a new vector “v” of type Vec<i32> to store the 32-bit signed integers. Alternatively, we can use the vec! macro to create a vector with initial elements:
With the basics out of the way, let us dive into how to sort the Rust vectors.
Method 1: Using the Sort Method
The sort method is one of the most common and basic methods of sorting a vector in Rust. This method is provided as part of the standard library.
The method signature is as follows:
where
Self: Ord,
Here, the “&mut self” indicates that the method takes a mutable reference to the slice to be sorted.
NOTE: The data type that is stored in the vector must implement the Ord trait which allows for sorting using various operators.
The method sorts a mutable slice of elements in ascending order. This means that we can use the method to sort the various Rust primitive types such as integers, floats, strings, arrays, and vectors.
Consider the following example that demonstrates how to use the sort() method to sort a Rust vector that contains the integer values:
let mut numbers = vec![487, 723, 123, 336, 534, 108, 422, 122, 143];
numbers.sort();
println!("{:?}", numbers);
}
In this example, we create a mutable vector which contains the integer values. We then call the sort method on the vector which sorts the elements in ascending order.
NOTE: The sort() method modifies the provided vector in place. Hence, we must ensure that the vector is mutable using the “mut” keyword.
Output:
We can also use this method to sort a floating point-value vector as demonstrated in the following:
let mut numbers = vec![4.5, 2.1, 1.3, 3.8, 5.2];
numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", numbers);
}
Output:
Although the previous method works, comparing the floating point values using the equality operator is not recommended due to rounding errors.
Instead, it is recommended to use the partial_cmp() method.
Rust also allows us to use the sort method to sort a struct as demonstrated in the following sample code:
struct Person {
name: String,
age: u32,
}
fn main() {
let mut people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 18 },
Person { name: "Charlie".to_string(), age: 32 },
];
// Sort the vector of people by age
people.sort_by(|a, b| a.age.cmp(&b.age));
println!("{:?}", people);
}
Output:
To sort the people vector by age in ascending order, we call the sort_by method on the vector and pass in a closure that compares the age fields of two “Person” objects.
We use the cmp method to compare the age fields which returns an ordering value that indicates whether the first object is less than, equal to, or greater than the second object.
Note: We need to pass a reference to the “b.age” field using the “&” operator since the cmp method expects a reference to the second argument.
Method 2: Using the Sort_By Method
Rust also provides us with the sort_by function that allows us to sort a vector with types that do not implement the Ord trait.
Example:
let mut words = vec!["apple", "banana", "cherry", "date", "elderberry"];
words.sort_by(|a, b| a.len().cmp(&b.len()));
println!("{:?}", words);
}
Note: The previous example does not mean that the strings do not implement the Ord trait.
Output:
Note: The sort_by method takes a closure that can compare the elements in any way that we like, not just by their natural ordering. Hence, we can use this feature to sort the elements by any property or criteria that we define.
Conclusion
You learned how you can use the Rust sort and sort_by method to sort a vector of various types.