計數排序假設n
個輸入元素都是0
到k
區間的一個整數(k
爲某整數)
當k
爲O(n)
時,排序的時間爲O(n)
數組
計數排序基本思想是:對於每一個輸入元素x
, 肯定小於x
的元素個數code
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); }