Radix sort

Radix sort is an algorithm that sorts integers in O(nw) time, where w denotes the storage size of the integers.

Briefly, it works like this:

Note that an implementation can start with either the LSB or the MSB.

Implementations

Rust

fn main() {
    let mut array: [u32; 10] = [523442, 2, 9, 49034394, 3, 42, 22, 13, 43043, 202032232];
    let mut out = [0; 10];

    println!("{:?}", array);
    for s in 0..4 {
        let mut counter = [0; 256];

        for &e in array.iter() {
            let e = (e >> (s * 8)) & 0xff;
            counter[e as usize] += 1;
        }

        let mut acc = 0;
        for e in counter.iter_mut() {
            let p = *e;
            *e = acc;
            acc += p;
        }

        for &e in array.iter() {
            let i = (e >> (s * 8)) & 0xff;
            out[counter[i as usize]] = e;
            counter[i as usize] += 1;
        }

        array = out;
        println!("{:?}", array);
    }
}