From ebff1cce9f13614d55bfa941c1c85decf353890b Mon Sep 17 00:00:00 2001 From: rongyi Date: Sat, 11 May 2024 17:59:44 +0800 Subject: [PATCH] Stick with swap (#1352) --- codes/rust/chapter_sorting/bubble_sort.rs | 8 ++------ codes/rust/chapter_sorting/heap_sort.rs | 8 ++------ 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/codes/rust/chapter_sorting/bubble_sort.rs b/codes/rust/chapter_sorting/bubble_sort.rs index d7fde10ae..2557a222f 100644 --- a/codes/rust/chapter_sorting/bubble_sort.rs +++ b/codes/rust/chapter_sorting/bubble_sort.rs @@ -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; // 记录交换元素 } } diff --git a/codes/rust/chapter_sorting/heap_sort.rs b/codes/rust/chapter_sorting/heap_sort.rs index 105ade56c..55ab52428 100644 --- a/codes/rust/chapter_sorting/heap_sort.rs +++ b/codes/rust/chapter_sorting/heap_sort.rs @@ -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); }