冒泡排序

This commit is contained in:
Shikong 2024-05-23 14:22:10 +08:00
parent 28e0ff58f7
commit f7e9470111
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
3 changed files with 24 additions and 1 deletions

View File

@ -15,4 +15,4 @@
fn main() {
println!("Hello, world!");
}
}

6
x.bubble_sort/Cargo.toml Normal file
View File

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

17
x.bubble_sort/src/main.rs Normal file
View File

@ -0,0 +1,17 @@
/// 冒泡排序算法
fn bubble_sort<T: Ord>(arr: &mut [T]) {
for i in 0..arr.len() {
for j in 0..arr.len() - 1 - i {
if arr[j] > arr[j + 1] {
arr.swap(j, j + 1);
}
}
}
}
fn main() {
let mut arr = vec![5, 3, 8, 4, 2, -1, 10];
println!("原始 array: {:?}", arr);
bubble_sort(&mut arr);
println!("排序 array: {:?}", arr);
}