It would be more idiomatic to make sort_vec
work with a mutable reference. This avoids cloning the original vector if you don't need to keep the original.
If you want to keep the original, I would clone it outside the sort_vec
function:
fn main() {
let vec1: Vec<i32> = vec![5, 6, 0, 4, 88, 2, 4, 9, 9, 54, 32, 1, 51, 7];
let mut sorted_vec = vec1.clone(); // assuming you want to keep the unsorted original
sort_vec(&mut sorted_vec);
for num in &sorted_vec {
println!("{}", num);
}
}
fn sort_vec(vector: &mut [i32]) {
let mut temp: i32;
let mut curnum: i32;
let mut num: i32;
for curidx in 0..vector.len() {
for idx in 0..vector.len() {
num = vector[idx];
curnum = vector[curidx];
if curidx == idx {
continue;
}
if curnum < num && curidx > idx {
temp = curnum;
vector[curidx] = num;
vector[idx] = temp;
}
}
}
}
(Playground)
Note that slice::sort
from the standard library also works on a &mut
reference.
Yes, the sorting algorithm itself is not efficient. idx
could start with curidx+1
instead of starting with 0
:
for curidx in 0..vector.len() {
- for idx in 0..vector.len() {
+ for idx in curidx + 1..vector.len() {
And also, curidx
doesn't need to run to vector.len()
but only to vector.len()-1
:
- for curidx in 0..vector.len() {
+ for curidx in 0..vector.len() - 1 {
for idx in curidx + 1..vector.len() {
Then you could remove all this:
- if curidx == idx {
- continue;
- }
- if curnum < num && curidx > idx {
+ if curnum > num {
temp = curnum;
vector[curidx] = num;
vector[idx] = temp;
}
Moreover, temp
isn't needed, because curnum
and num
are copies already:
- temp = curnum;
vector[curidx] = num;
- vector[idx] = temp;
+ vector[idx] = curnum;
You don't need curnum
and num
to be mutable, instead you can just declare them with a more limited scope:
fn sort_vec(vector: &mut [i32]) {
- let mut temp: i32;
- let mut curnum: i32;
- let mut num: i32;
for curidx in 0..vector.len() - 1 {
for idx in curidx + 1..vector.len() {
- num = vector[idx];
+ let num = vector[idx];
- curnum = vector[curidx];
+ let curnum = vector[curidx];
if curnum > num {
vector[curidx] = num;
vector[idx] = curnum;
}
}
}
}
That said, @alice pointed out already, that Rust provides a function for swapping (which you could also use): slice::swap
.
Here is a cleaned up version, which doesn't use the methods from std
:
fn sort_vec(vector: &mut [i32]) {
for curidx in 0..vector.len() - 1 {
for idx in curidx + 1..vector.len() {
let num = vector[idx];
let curnum = vector[curidx];
if curnum > num {
vector[curidx] = num;
vector[idx] = curnum;
}
}
}
}
(Playground)
But even that algorithm is still not very efficient. There are better sorting algorithms, see Wikipedia for some examples.
Yeah, or this way. In my example curidx
is smaller than idx
and I changed the comparison.