Skip to content

Commit

Permalink
[Rust] No need to use mut iter (krahets#1356)
Browse files Browse the repository at this point in the history
* No need to use mut iter

* Update iter
  • Loading branch information
rongyi authored May 12, 2024
1 parent ebff1cc commit 063a41f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
6 changes: 3 additions & 3 deletions codes/rust/chapter_sorting/bucket_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}
Expand Down
16 changes: 7 additions & 9 deletions codes/rust/chapter_sorting/counting_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 */
Expand Down

0 comments on commit 063a41f

Please sign in to comment.