Skip to content

Commit

Permalink
sorts: Fix position error in selection sort
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Nov 15, 2023
1 parent 5f0c3d8 commit beedec6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
10 changes: 8 additions & 2 deletions robert/src/bin/selection_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use robert::util::{read_ints, show};
use robert::util::{is_sorted, read_ints, show};
use sorts::selection_sort;

fn main() {
let mut list = read_ints();
selection_sort(&mut list);
assert!(is_sorted(&list));
println!("RESULT:");
show(&list);
if list.len() < 128 {
show(&list);
} else {
show(&list[..128]);
println!("...\n...");
}
}
10 changes: 8 additions & 2 deletions robert/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::fmt;
use std::io::{self, BufRead, BufReader};

pub fn exch<T>(list: &mut Vec<T>, i: usize, j: usize)
Expand All @@ -15,10 +16,15 @@ where

pub fn is_sorted<T>(list: &[T]) -> bool
where
T: PartialOrd,
T: PartialOrd + fmt::Debug,
{
for i in 0..(list.len() - 1) {
if list[i] > list[i + 1] {
println!(
"Order error at: {i}, values: ({:?}, {:?})",
list[i],
list[i + 1]
);
return false;
}
}
Expand All @@ -27,7 +33,7 @@ where

pub fn show<T>(vec: &[T])
where
T: std::fmt::Display,
T: fmt::Display,
{
for s in vec {
print!("{} ", s);
Expand Down
21 changes: 17 additions & 4 deletions sorts/src/selection_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ pub fn selection_sort(list: &mut [i32]) {
for i in 0..(len - 1) {
let mut min_index = i;
for j in (i + 1)..len {
if list[min_index] > list[j] {
if list[j] < list[min_index] {
min_index = j;
}
if i != min_index {
list.swap(i, min_index);
}
}
if i != min_index {
list.swap(i, min_index);
}
}
}
Expand All @@ -51,5 +51,18 @@ mod tests {
let mut list = [-2, -5, -45];
selection_sort(&mut list);
assert_eq!(list, [-45, -5, -2]);

let mut list = [
-998166, -996360, -995703, -995238, -995066, -994740, -992987, -983833, -987905,
-980069, -977640,
];
selection_sort(&mut list);
assert_eq!(
list,
[
-998166, -996360, -995703, -995238, -995066, -994740, -992987, -987905, -983833,
-980069, -977640,
]
);
}
}

0 comments on commit beedec6

Please sign in to comment.