Stick with swap (#1352)

This commit is contained in:
rongyi 2024-05-11 17:59:44 +08:00 committed by GitHub
parent 7a96f6a743
commit ebff1cce9f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 4 additions and 12 deletions

View file

@ -14,9 +14,7 @@ fn bubble_sort(nums: &mut [i32]) {
for j in 0..i { for j in 0..i {
if nums[j] > nums[j + 1] { if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1] // 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]; nums.swap(j, j + 1);
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
} }
} }
} }
@ -31,9 +29,7 @@ fn bubble_sort_with_flag(nums: &mut [i32]) {
for j in 0..i { for j in 0..i {
if nums[j] > nums[j + 1] { if nums[j] > nums[j + 1] {
// 交换 nums[j] 与 nums[j + 1] // 交换 nums[j] 与 nums[j + 1]
let tmp = nums[j]; nums.swap(j, j + 1);
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 记录交换元素 flag = true; // 记录交换元素
} }
} }

View file

@ -24,9 +24,7 @@ fn sift_down(nums: &mut [i32], n: usize, mut i: usize) {
break; break;
} }
// 交换两节点 // 交换两节点
let temp = nums[i]; nums.swap(i, ma);
nums[i] = nums[ma];
nums[ma] = temp;
// 循环向下堆化 // 循环向下堆化
i = ma; i = ma;
} }
@ -41,9 +39,7 @@ fn heap_sort(nums: &mut [i32]) {
// 从堆中提取最大元素,循环 n-1 轮 // 从堆中提取最大元素,循环 n-1 轮
for i in (1..nums.len()).rev() { for i in (1..nums.len()).rev() {
// 交换根节点与最右叶节点(交换首元素与尾元素) // 交换根节点与最右叶节点(交换首元素与尾元素)
let tmp = nums[0]; nums.swap(0, i);
nums[0] = nums[i];
nums[i] = tmp;
// 以根节点为起点,从顶至底进行堆化 // 以根节点为起点,从顶至底进行堆化
sift_down(nums, i, 0); sift_down(nums, i, 0);
} }