diff --git a/2.hello_cargo/src/main.rs b/2.hello_cargo/src/main.rs index 6a27613..8569947 100644 --- a/2.hello_cargo/src/main.rs +++ b/2.hello_cargo/src/main.rs @@ -15,4 +15,4 @@ fn main() { println!("Hello, world!"); -} +} \ No newline at end of file diff --git a/x.bubble_sort/Cargo.toml b/x.bubble_sort/Cargo.toml new file mode 100644 index 0000000..45f24f8 --- /dev/null +++ b/x.bubble_sort/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "bubble_sort" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/x.bubble_sort/src/main.rs b/x.bubble_sort/src/main.rs new file mode 100644 index 0000000..11c55c3 --- /dev/null +++ b/x.bubble_sort/src/main.rs @@ -0,0 +1,17 @@ +/// 冒泡排序算法 +fn bubble_sort(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); +}