Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array?

Tags:

rust

Why cannot I not sort an array as expected?

fn main() {
    let mut a = [1,3,2];
    let s = a.sort();
    println!("{:?}", s);
}
like image 632
Lars Rönnbäck Avatar asked Jul 03 '17 14:07

Lars Rönnbäck


People also ask

How do you sort an array in C++?

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.

What does arrays sort () do?

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.

How do you sort an array in a function?

Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.


1 Answers

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);
}

Writing a function that returns a sorted array

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]);
}
like image 109
Boiethios Avatar answered Sep 29 '22 20:09

Boiethios