From 063a41fa7f4ad1def279945a1882977d4eb3d098 Mon Sep 17 00:00:00 2001 From: rongyi Date: Sun, 12 May 2024 14:49:25 +0800 Subject: [PATCH] [Rust] No need to use mut iter (#1356) * No need to use mut iter * Update iter --- codes/rust/chapter_sorting/bucket_sort.rs | 6 +++--- codes/rust/chapter_sorting/counting_sort.rs | 16 +++++++--------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/codes/rust/chapter_sorting/bucket_sort.rs b/codes/rust/chapter_sorting/bucket_sort.rs index 5bec09451..02e09abf2 100644 --- a/codes/rust/chapter_sorting/bucket_sort.rs +++ b/codes/rust/chapter_sorting/bucket_sort.rs @@ -12,7 +12,7 @@ fn bucket_sort(nums: &mut [f64]) { let k = nums.len() / 2; let mut buckets = vec![vec![]; k]; // 1. 将数组元素分配到各个桶中 - for &mut num in &mut *nums { + for &num in nums.iter() { // 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1] let i = (num * k as f64) as usize; // 将 num 添加进桶 i @@ -25,8 +25,8 @@ fn bucket_sort(nums: &mut [f64]) { } // 3. 遍历桶合并结果 let mut i = 0; - for bucket in &mut buckets { - for &mut num in bucket { + for bucket in buckets.iter() { + for &num in bucket.iter() { nums[i] = num; i += 1; } diff --git a/codes/rust/chapter_sorting/counting_sort.rs b/codes/rust/chapter_sorting/counting_sort.rs index ca4ed0de3..c6a5d92cd 100644 --- a/codes/rust/chapter_sorting/counting_sort.rs +++ b/codes/rust/chapter_sorting/counting_sort.rs @@ -10,11 +10,11 @@ include!("../include/include.rs"); // 简单实现,无法用于排序对象 fn counting_sort_naive(nums: &mut [i32]) { // 1. 统计数组最大元素 m - let m = *nums.into_iter().max().unwrap(); + let m = *nums.iter().max().unwrap(); // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 let mut counter = vec![0; m as usize + 1]; - for &num in &*nums { + for &num in nums.iter() { counter[num as usize] += 1; } // 3. 遍历 counter ,将各元素填入原数组 nums @@ -31,16 +31,16 @@ fn counting_sort_naive(nums: &mut [i32]) { // 完整实现,可排序对象,并且是稳定排序 fn counting_sort(nums: &mut [i32]) { // 1. 统计数组最大元素 m - let m = *nums.into_iter().max().unwrap(); + let m = *nums.iter().max().unwrap() as usize; // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 - let mut counter = vec![0; m as usize + 1]; - for &num in &*nums { + let mut counter = vec![0; m + 1]; + for &num in nums.iter() { counter[num as usize] += 1; } // 3. 求 counter 的前缀和,将“出现次数”转换为“尾索引” // 即 counter[num]-1 是 num 在 res 中最后一次出现的索引 - for i in 0..m as usize { + for i in 0..m { counter[i + 1] += counter[i]; } // 4. 倒序遍历 nums ,将各元素填入结果数组 res @@ -53,9 +53,7 @@ fn counting_sort(nums: &mut [i32]) { counter[num as usize] -= 1; // 令前缀和自减 1 ,得到下次放置 num 的索引 } // 使用结果数组 res 覆盖原数组 nums - for i in 0..n { - nums[i] = res[i]; - } + nums.copy_from_slice(&res) } /* Driver Code */