From f7e947011127e980b7faf0129717f0a814757a8c Mon Sep 17 00:00:00 2001 From: Shikong <919411476@qq.com> Date: Thu, 23 May 2024 14:22:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=86=92=E6=B3=A1=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2.hello_cargo/src/main.rs | 2 +- x.bubble_sort/Cargo.toml | 6 ++++++ x.bubble_sort/src/main.rs | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 x.bubble_sort/Cargo.toml create mode 100644 x.bubble_sort/src/main.rs 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); +}