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 {
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; // 记录交换元素
}
}

View file

@ -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);
}