Skip to content

Commit

Permalink
sorts: Add binary targets
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 13, 2023
1 parent f2397c6 commit 72c57c5
Show file tree
Hide file tree
Showing 10 changed files with 270 additions and 0 deletions.
56 changes: 56 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sorts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ edition = "2021"
publish = false

[dependencies]
rand = "0.8.5"
16 changes: 16 additions & 0 deletions sorts/src/bin/bubble_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use sorts::bubble_sort;
use sorts::util::{is_sorted, read_ints, show_brief};

fn main() {
let mut list = read_ints();
println!("[BubbleSort] LIST:");
show_brief(&list);
bubble_sort(&mut list);
println!("RESULT:");
assert!(is_sorted(&list));
show_brief(&list);
}
20 changes: 20 additions & 0 deletions sorts/src/bin/insertion_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use sorts::util::{is_sorted, read_ints, show_brief};
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));
}
16 changes: 16 additions & 0 deletions sorts/src/bin/merge_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use sorts::merge_sort;
use sorts::util::{is_sorted, read_ints, show_brief};

fn main() {
let mut list = read_ints();
println!("[MergeSort] list");
show_brief(&list);
merge_sort(&mut list);
println!("Result:");
show_brief(&list);
assert!(is_sorted(&list));
}
14 changes: 14 additions & 0 deletions sorts/src/bin/selection_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use sorts::selection_sort;
use sorts::util::{is_sorted, read_ints, show_brief};

fn main() {
let mut list = read_ints();
selection_sort(&mut list);
assert!(is_sorted(&list));
println!("RESULT:");
show_brief(&list);
}
16 changes: 16 additions & 0 deletions sorts/src/bin/shell_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use sorts::shell_sort;
use sorts::util::{is_sorted, read_ints, show_brief};

fn main() {
let mut list = read_ints();
println!("[ShellSort] LIST:");
show_brief(&list);
shell_sort(&mut list);
println!("RESULT:");
assert!(is_sorted(&list));
show_brief(&list);
}
54 changes: 54 additions & 0 deletions sorts/src/bin/sort_compare.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use rand::Rng;
use std::time::Instant;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SortVariant {
Insertion,
Selection,
Shell,
}

fn time_sort(array: &mut [f64], variant: SortVariant) -> u128 {
let instance = Instant::now();
match variant {
SortVariant::Insertion => sorts::insertion_sort(array),
SortVariant::Selection => sorts::selection_sort(array),
SortVariant::Shell => sorts::shell_sort(array),
}
instance.elapsed().as_nanos()
}

fn time_random_input(variant: SortVariant, len: usize, times: i32) -> u128 {
let mut total = 0;
let mut rng = rand::thread_rng();
let mut array = vec![0.0; len];
for _t in 0..times {
for item in array.iter_mut() {
*item = rng.gen();
}
total += time_sort(&mut array, variant);
}

total
}

fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
panic!("Usage: number times");
}
let num: usize = args[1].parse().expect("Invalid total length");
let times: i32 = args[2].parse().expect("Invalid times");
let t1 = time_random_input(SortVariant::Insertion, num, times);
let t2 = time_random_input(SortVariant::Selection, num, times);
let t3 = time_random_input(SortVariant::Shell, num, times);

println!("Insertion: {t1}, Selection: {t2}, ShellSort: {t3}");
let ratio1: f64 = (t1 as f64) / (t3 as f64);
let ratio2: f64 = t2 as f64 / t3 as f64;
println!("Insertion ratio: {ratio1:.2}, Selection ratio: {ratio2:.2}, Shell ratio: 1.0");
}
1 change: 1 addition & 0 deletions sorts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod odd_even_sort;
mod selection_sort;
mod shaker_sort;
mod shell_sort;
pub mod util;

pub use bubble_sort::bubble_sort;
pub use double_sort::double_sort;
Expand Down
76 changes: 76 additions & 0 deletions sorts/src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) 2020 Xu Shaohua <[email protected]>. All rights reserved.
// 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 is_sorted<T>(list: &[T]) -> bool
where
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;
}
}
true
}

pub fn show<T>(slice: &[T])
where
T: fmt::Display,
{
for s in slice {
print!("{s} ");
}
println!();
}

pub fn show_brief<T>(slice: &[T])
where
T: fmt::Display,
{
if slice.len() < 128 {
show(slice);
} else {
show(&slice[..128]);
println!("...\n...");
}
}

/// Read integers from stdin.
///
/// # Panics
/// Raise panic if invalid integer found.
#[must_use]
pub fn read_ints() -> Vec<i32> {
let mut v = vec![];
let buffer = BufReader::new(io::stdin());
let input_iter = buffer.lines();
for line in input_iter.flatten() {
for word in line.split_whitespace() {
let value = word.parse::<i32>().expect("Invalid integer");
v.push(value);
}
}
v
}

#[must_use]
pub fn read_strings() -> Vec<String> {
let buffer = BufReader::new(io::stdin());
let input_iter = buffer.lines();
let mut v = vec![];
for line in input_iter.flatten() {
for word in line.split_whitespace() {
v.push(word.to_string());
}
}
v
}

0 comments on commit 72c57c5

Please sign in to comment.