Why cannot I not sort an array as expected?
fn main() {
let mut a = [1,3,2];
let s = a.sort();
println!("{:?}", s);
}
Here, first – is the index (pointer) of the first element in the range to be sorted. last – is the index (pointer) of the last element in the range to be sorted. For example, we want to sort elements of an array 'arr' from 1 to 10 position, we will use sort(arr, arr+10) and it will sort 10 elements in Ascending order.
The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.
a
is sorted, but the method sorts the array in place. Read the signature of sort
: sort
takes &mut self
and returns unit (i.e. nothing), so when you print s
, you print ()
.
Working code:
fn main() {
let mut a = [1, 3, 2];
a.sort();
assert_eq!(a, [1, 2, 3]);
println!("{:?}", a);
}
You can write a function that does what you want:
fn sort<A, T>(mut array: A) -> A
where
A: AsMut<[T]>,
T: Ord,
{
let slice = array.as_mut();
slice.sort();
array
}
fn main() {
let a = [1, 3, 2];
assert_eq!(sort(a), [1, 2, 3]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With