added selection sort

This commit is contained in:
2024-07-27 15:53:18 +02:00
commit 94f1da1e3d
4 changed files with 43 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "algodat"
version = "0.1.0"

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "algodat"
version = "0.1.0"
edition = "2021"
[dependencies]

29
src/lib.rs Normal file
View File

@ -0,0 +1,29 @@
#![feature(is_sorted)]
pub fn selection_sort<T: PartialOrd>(arr: &mut Vec<T>){
let mut index: usize = 0;
while let Some(mut smallest) = arr.get(index) {
let mut smallest_index = index;
for (item_index, item) in arr[index..].iter().enumerate() {
if smallest > item {
smallest = item;
smallest_index = item_index + index;
}
}
arr.swap(index, smallest_index);
index += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let mut v = vec![2, 3, 1, 7, 21, 1337, 420];
selection_sort(&mut v);
assert!(dbg!(v).is_sorted());
}
}