Rust offers built-in functions, namely sort()
and sort_by()
, that can be used to sort vectors. Now, let's look at each of these functions and discuss how they can be used.
sort()
functionThe sort()
function sorts a vector by accepting an unsorted vector and generating a sorted one in which the underlying elements are sorted in ascending order by default. Sorting in reverse order is also possible and can be done by adding the reverse keyword, as seen in the example below.
This basic example shows how to sort a vector of integer values using the sort()
function:
fn main() {let mut v = vec![0, 10, 5, 15, 25, 1, -10, 10, 50000];println!("The Vector before sorting = {:?}", v);v.sort();println!("The vector sorted in asc order = {:?}", v);v.reverse();println!("The vector sorted in desc order = {:?}", v);}
Let's go through the code above:
Line 2: Declare a vector of integer values.
Line 3: Print out the vector before sorting.
Line 4: Invoke the sort()
function to sort the vector elements in ascending order.
Line 5: Print out the sorted vector.
Line 6: Call the reverse()
function to sort the vector in reverse or descending order.
Line 7: Print out the vector sorted in descending order.
Now, let's explore another function, sort_by()
, to sort a vector.
sort_by()
functionThe sort_by()
function sorts a vector based on a
This example illustrates the usage of the sort_by
function:
fn main() {let mut names = vec!["Bassem", "Celeste", "Rick","Valentine"];println!("The Vector before sorting = {:?}", names);names.sort_by(|a, b| a.len().cmp(&b.len()));println!("The sorted vector = {:?}", names);}
Let's go through the code above:
Line 2: Declare a vector called names
composed of string values.
Line 3: Print out this vector before sorting.
Line 4: Invoke the function sort_by()
while specifying a comparator function cmp
that allows sorting the specified vector's underlying elements based on their length. The sort_by()
function slices the elements of the considered vector and iterates over them while applying the comparator function cmp
. The cmp
method is used to perform the comparison between the elements of each slice; it compares them based on their length, extracted using the len()
function. As a result, we'll get a vector sorted based on the length of its elements.
Line 5: Print out the sorted vector.
Free Resources