algorithms_fourth/string/
msd.rs1use crate::insert_sort;
11const M: usize = 0;
15const R: usize = 256;
17pub fn sort(src: &mut Vec<&str>) {
18 let n = src.len();
19 let mut aux = vec![""; n];
20 sort_in_range(src, &mut aux, 0, n - 1, 0);
21}
22
23fn sort_in_range<'a>(src: &mut [&'a str], aux: &mut [&'a str], lo: usize, hi: usize, d: usize) {
24 if hi <= lo {
25 return;
26 }
27 if hi <= lo + M {
28 insert_sort(src);
30 return;
31 }
32 let mut count = [0; R + 2];
33 for i in lo..=hi {
34 count[char_at(src[i], d) + 1] += 1;
37 }
38 for r in 0..R + 1 {
39 count[r + 1] += count[r];
41 }
42
43 (lo..=hi).for_each(|i| {
44 let pos = char_at(src[i], d);
47 aux[count[pos]] = src[i];
49 count[pos] += 1;
50 });
51 (lo..=hi).for_each(|i| {
52 src[i] = aux[i - lo];
54 });
55 let d = d + 1;
56 for i in 0..R {
57 if count[i] < count[i + 1] {
58 sort_in_range(src, aux, lo + count[i], lo + count[i + 1] - 1, d);
59 }
60 }
61}
62fn char_at(s: &str, d: usize) -> usize {
66 s.as_bytes().get(d).map_or(0, |&f| f as usize + 1)
67}
68#[cfg(test)]
69mod test {
70 use super::sort;
71
72 #[test]
73 fn test() {
74 let mut src = vec![
75 "she",
76 "a",
77 "",
78 "sells",
79 "seashells",
80 "by",
81 "the",
82 "sea",
83 "shore",
84 "the",
85 "shells",
86 "shea",
87 "sells",
88 "are",
89 "surely",
90 "seashells",
91 ];
92 sort(&mut src);
93 println!("{:?}", src);
94 }
95}