Skip to content

Commit

Permalink
sorts: Add selection sort
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Nov 15, 2023
1 parent 74fece5 commit 014a3d2
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 12 deletions.
23 changes: 11 additions & 12 deletions sorts/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
}
// Copyright (c) 2023 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.

#[cfg(test)]
mod tests {
use super::*;
#![deny(
warnings,
clippy::all,
clippy::cargo,
clippy::nursery,
clippy::pedantic
)]

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
pub mod selection_sort;
52 changes: 52 additions & 0 deletions sorts/src/selection_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) 2023 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.

/// Selection sort works as follows:
/// - Find the smallest element in the array, and exchange it with the first
/// element in the array.
/// - Find the second smallest element in the array, and exchange it with the
/// element in the second position.
/// - Continue in this way until the entire array is sorted.
///
/// It takes about as long to run selection sort for a file that is already
/// in order, or for a file with all keys equal, as it does for a randomly
/// ordered file.
///
/// It is the method of choice for sorting files with huge items and small keys.
/// For such applications, the cost of moving the data dominates the cost of
/// making comparisons, and no algorithms can sort a file with substantially less
/// data movement than selection sort.
pub fn selection_sort(list: &mut [i32]) {
if list.is_empty() {
return;
}
let len = list.len();
for i in 0..(len - 1) {
let mut min_index = i;
for j in (i + 1)..len {
if list[min_index] > list[j] {
min_index = j;
}
if i != min_index {
list.swap(i, min_index);
}
}
}
}

#[cfg(test)]
mod tests {
use super::selection_sort;

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

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

0 comments on commit 014a3d2

Please sign in to comment.