Rust 基数排序
参数是数组,改成Vec也可以,中间实现比较垃圾,凑合用
use std::collections::VecDeque;
fn radix_sort(v:&mut [i32]){
let lenght = v.len();
let max = *v.iter().max().unwrap();
let mut digit = 1;
let radix = 10;
let mut matrix = Vec::new();
for _ in 0..lenght{
matrix.push(VecDeque::new());
}
let mut index;
while digit<=max {
index = 0;
for i in 0..lenght{
matrix[(v[i]/digit%radix) as usize].push_back(v[i]);
}
for i in 0..lenght{
while !matrix[i].is_empty() {
v[index]=matrix[i].pop_front().unwrap(); // 从队列头pop元素,vec没有这个功能,直接用自带的VecDeque就可以有pop_front方法
index+=1;
}
if index==lenght{ // 稍微添加一个判断条件,可要可不要,用作优化
break;
}
}
digit *= radix;
}
}
fn main() {
let mut v = [32,43,47,32,32,12,4,5,356,2,125,23,13,2,46,26,7,2,3,7,5,52,12,7,67,68,45];
radix_sort(&mut v);
println!("{:?}",v);
}