This commit is contained in:
krahets
2023-07-26 10:57:40 +08:00
parent 6381f16506
commit f8f7086196
52 changed files with 4032 additions and 0 deletions
+43
View File
@@ -255,6 +255,26 @@ comments: true
}
```
=== "Rust"
```rust title="bubble_sort.rs"
/* 冒泡排序 */
fn bubble_sort(nums: &mut [i32]) {
// 外循环:未排序区间为 [0, i]
for i in (1..nums.len()).rev() {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0..i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
```
## 11.3.2.   效率优化
我们发现,如果某轮“冒泡”中没有执行任何交换操作,说明数组已经完成排序,可直接返回结果。因此,可以增加一个标志位 `flag` 来监测这种情况,一旦出现就立即返回。
@@ -514,6 +534,29 @@ comments: true
}
```
=== "Rust"
```rust title="bubble_sort.rs"
/* 冒泡排序(标志优化) */
fn bubble_sort_with_flag(nums: &mut [i32]) {
// 外循环:未排序区间为 [0, i]
for i in (1..nums.len()).rev() {
let mut flag = false; // 初始化标志位
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
for j in 0..i {
if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 记录交换元素
}
}
if !flag {break}; // 此轮冒泡未交换任何元素,直接跳出
}
}
```
## 11.3.3.   算法特性
- **时间复杂度为 $O(n^2)$ 、自适应排序** :各轮“冒泡”遍历的数组长度依次为 $n - 1$ , $n - 2$ , $\cdots$ , $2$ , $1$ ,总和为 $\frac{(n - 1) n}{2}$ 。在引入 `flag` 优化后,最佳时间复杂度可达到 $O(n)$ 。