From beedec68b8c654814c57f8a57e2fc566aa529df0 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Wed, 15 Nov 2023 20:34:34 +0800 Subject: [PATCH] sorts: Fix position error in selection sort --- robert/src/bin/selection_sort.rs | 10 ++++++++-- robert/src/util.rs | 10 ++++++++-- sorts/src/selection_sort.rs | 21 +++++++++++++++++---- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/robert/src/bin/selection_sort.rs b/robert/src/bin/selection_sort.rs index 0d3710c0..4e0c35ed 100644 --- a/robert/src/bin/selection_sort.rs +++ b/robert/src/bin/selection_sort.rs @@ -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..."); + } } diff --git a/robert/src/util.rs b/robert/src/util.rs index bebb7c0c..4f66a72d 100644 --- a/robert/src/util.rs +++ b/robert/src/util.rs @@ -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(list: &mut Vec, i: usize, j: usize) @@ -15,10 +16,15 @@ where pub fn is_sorted(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; } } @@ -27,7 +33,7 @@ where pub fn show(vec: &[T]) where - T: std::fmt::Display, + T: fmt::Display, { for s in vec { print!("{} ", s); diff --git a/sorts/src/selection_sort.rs b/sorts/src/selection_sort.rs index 6455e2f0..f3371f6d 100644 --- a/sorts/src/selection_sort.rs +++ b/sorts/src/selection_sort.rs @@ -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); } } } @@ -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, + ] + ); } }