Skip to content

Commit

Permalink
sorts: Add insertion sort vanilla
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Nov 16, 2023
1 parent 5ca7d2a commit 3045ca8
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 2 deletions.
6 changes: 5 additions & 1 deletion robert/src/bin/insertion_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
// in the LICENSE file.

use robert::util::{is_sorted, read_ints, show_brief};
use sorts::insertion_sort;
use sorts::{insertion_sort, insertion_sort_vanilla};

fn main() {
let mut list = read_ints();
println!("[InsertionSort] LIST:");
show_brief(&list);
let mut list2 = list.clone();
insertion_sort(&mut list);
println!("RESULT:");
assert!(is_sorted(&list));
show_brief(&list);

insertion_sort_vanilla(&mut list2);
assert!(is_sorted(&list2));
}
68 changes: 68 additions & 0 deletions sorts/src/insertion_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,71 @@ where
}
}
}

/// Insertion sort, no optimization.
pub fn insertion_sort_vanilla<T>(list: &mut [T])
where
T: PartialOrd,
{
let len = list.len();
for i in 1..len {
for j in (1..=i).rev() {
if list[j - 1] > list[j] {
list.swap(j - 1, j);
}
}
}
}

#[cfg(test)]
mod tests {
use super::{insertion_sort, insertion_sort_vanilla};

#[test]
fn test_insertion_sort() {
let mut list = [0, 5, 3, 2, 2];
insertion_sort(&mut list);
assert_eq!(list, [0, 2, 2, 3, 5]);

let mut list = [-2, -5, -45];
insertion_sort(&mut list);
assert_eq!(list, [-45, -5, -2]);

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

#[test]
fn test_insertion_sort_vanilla() {
let mut list = [0, 5, 3, 2, 2];
insertion_sort_vanilla(&mut list);
assert_eq!(list, [0, 2, 2, 3, 5]);

let mut list = [-2, -5, -45];
insertion_sort_vanilla(&mut list);
assert_eq!(list, [-45, -5, -2]);

let mut list = [
-998166, -996360, -995703, -995238, -995066, -994740, -992987, -983833, -987905,
-980069, -977640,
];
insertion_sort_vanilla(&mut list);
assert_eq!(
list,
[
-998166, -996360, -995703, -995238, -995066, -994740, -992987, -987905, -983833,
-980069, -977640,
]
);
}
}
2 changes: 1 addition & 1 deletion sorts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
)]

mod insertion_sort;
pub use insertion_sort::insertion_sort;
pub use insertion_sort::{insertion_sort, insertion_sort_vanilla};

mod selection_sort;
pub use selection_sort::selection_sort;

0 comments on commit 3045ca8

Please sign in to comment.