Hi folks, wish you're doing fine!
Could anyone help explain the sort() api for slice from the std lib a bit more to me... because I'm not sure whether I should use it in sorting algorithms implementations..
Taking the bubble_sort() implementation as an example, it seems that I could NEVER pass the test without this sort() api @ln2, but don't know why it should be like that?
And also wondering why still have to implement sorting algorithm when this std api can already sort slice in asc order in the 1st place?)
Here is my code (pls kindly refer)![]()
They both seem to stop at the end of single pass (without moving to next loop, which is weird..)
fn bubble_sort<T>(arr: &mut [T]) -> &[T] where T: Ord + PartialEq + Eq {
// arr.sort(); // I need to activate this to pass the test
for i in 0..arr.len() - 1 {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
}
}
arr
}
mod test {
use super::*;
#[test]
fn shoud_work1() {
let mut vec = [1, 2, 5, 4, 3];
let res = bubble_sort(&mut vec);
assert_eq!(res, &[1, 2, 3, 4, 5]);
}
#[test]
fn shoud_work2() {
let mut vec = [5, 4, 3, 2, 1];
let res = bubble_sort(&mut vec);
assert_eq!(res, &[1, 2, 3, 4, 5]);
}
thread 'test::shoud_work1' (47) panicked at src/lib.rs:73:9:
assertion `left == right` failed
left: [1, 2, 4, 3, 5]
right: [1, 2, 3, 4, 5]
---- test::shoud_work2 stdout ----
thread 'test::shoud_work2' (48) panicked at src/lib.rs:79:9:
assertion `left == right` failed
left: [4, 3, 2, 1, 5]
right: [1, 2, 3, 4, 5]