fn bucket_sort(arr: &[usize]) -> std::vec::Vec<usize> {
if arr.is_empty() {
return vec![];
}
let len = arr.len();
let max = arr.iter().max().unwrap();
let mut buckets = vec![vec![]; len + 1];
for vp in arr.iter() {
let value = *vp;
let idx = len * value / max;
// 分桶規則一定要定好,對於每個桶一定保證
// x < y && max(x) < min(y)
buckets[idx].push(value);
}
// 桶內排序
for bucket in buckets.iter_mut() {
super::insertion_sort::insertion_sort(bucket);
}
let mut res = vec![];
// 直接收集
for bucket in buckets.iter() {
for vp in bucket {
res.push(*vp);
}
}
res
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結