标签:capacity 计数 rust 可变 输入 初始化 int for city
计数排序假设n
个输入元素都是0
到k
区间的一个整数(k
为某整数)
当k
为O(n)
时,排序的时间为O(n)
计数排序基本思想是:对于每个输入元素x
, 确定小于x
的元素个数
let mut c: Vec<usize> = Vec::with_capacity(k);
for i in 0..k+1 {
c.push(0);
}
for i in 0..a.len() {
c[a[i]] = c[a[i]] + 1;
}
i
从0..k
, 有多少个元素是小于等于i
for i in 1..k+1 {
c[i] = c[i] + c[i-1];
}
for i in (0..a.len()).rev() {
b[c[a[i]]-1] = a[i];
c[a[i]] = c[a[i]] - 1;
}
O(k+n)
, 当k=O(n)
时, 一般会采用计数排序fn count_sort(a: &mut [usize], b: &mut [usize], k: usize) {
let mut c: Vec<usize> = Vec::with_capacity(k+1);
for _ in 0..k+1 {
c.push(0);
}
for i in 0..a.len() {
c[a[i]] = c[a[i]] + 1;
}
for i in 1..k+1 {
c[i] = c[i] + c[i-1];
}
for i in (0..a.len()).rev() {
b[c[a[i]]-1] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
fn main() {
let mut a: [usize; 8] = [2,5,3,0,2,3,0,3];
let mut b = [0usize; 8];
count_sort(&mut a, &mut b, 5);
println!("{:?}", b);
}
标签:capacity 计数 rust 可变 输入 初始化 int for city
原文地址:https://www.cnblogs.com/kwebi/p/9644536.html