mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-24 10:16:28 +08:00
Stick with swap (#1352)
This commit is contained in:
parent
7a96f6a743
commit
ebff1cce9f
2 changed files with 4 additions and 12 deletions
|
@ -14,9 +14,7 @@ fn bubble_sort(nums: &mut [i32]) {
|
|||
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;
|
||||
nums.swap(j, j + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -31,9 +29,7 @@ fn bubble_sort_with_flag(nums: &mut [i32]) {
|
|||
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;
|
||||
nums.swap(j, j + 1);
|
||||
flag = true; // 记录交换元素
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,9 +24,7 @@ fn sift_down(nums: &mut [i32], n: usize, mut i: usize) {
|
|||
break;
|
||||
}
|
||||
// 交换两节点
|
||||
let temp = nums[i];
|
||||
nums[i] = nums[ma];
|
||||
nums[ma] = temp;
|
||||
nums.swap(i, ma);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
|
@ -41,9 +39,7 @@ fn heap_sort(nums: &mut [i32]) {
|
|||
// 从堆中提取最大元素,循环 n-1 轮
|
||||
for i in (1..nums.len()).rev() {
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
let tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
nums.swap(0, i);
|
||||
// 以根节点为起点,从顶至底进行堆化
|
||||
sift_down(nums, i, 0);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue