Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created November 17, 2018 10:58
Show Gist options
  • Save rust-play/b077d94b835f0e6b1f5aeb1e34ea219a to your computer and use it in GitHub Desktop.
Save rust-play/b077d94b835f0e6b1f5aeb1e34ea219a to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
extern crate num; // 0.2.0
use num::{Zero, One};
use std::ops::{Shr, BitAnd};
fn main() {
let mut foo: Vec<u32> = vec![5, 3, 8, 10, 1093, 283, 5734, 7383, 3273, 18];
unsigned_radix_sort(&mut foo);
println!("{:?}", foo);
}
fn unsigned_radix_sort<T, R>(mut s: R)
where
T: Copy + Clone + BitAnd<Output = T> + Shr<usize, Output = T> + Zero
+ One + PartialEq,
<T as Shr<usize>>::Output: Into<T>,
R: AsMut<[T]>, {
let rmslice = s.as_mut();
if std::mem::size_of::<T>() == 0 || rmslice.len() == 0
|| rmslice.len() == 1 {
return;
} else {
let last = rmslice.len() - 1;
let mut count = 0;
let start_shift = std::mem::size_of::<T>() - 1;
for mut ind in 0..rmslice.len() {
if (rmslice[ind] >> start_shift).into() & T::zero() == T::one() {
rmslice.swap(ind, last);
ind -= 1;
} else {
count += 1;
}
}
unsigned_sort_at_bit(rmslice[0..count + 1], start_shift - 1);
unsigned_sort_at_bit(rmslice[count + 1..last + 1], start_shift - 1);
}
}
fn unsigned_sort_at_bit<T, R>(mut s: R, bit: usize)
where
T: Copy + Clone + BitAnd<Output = T> + Shr<usize, Output = T> + Zero
+ One + PartialEq,
R: AsMut<[T]>, {
let rmslice = s.as_mut();
if rmslice.len() == 0 || rmslice.len() == 1 {
return;
} else {
let last = rmslice.len() - 1;
let mut count = 0;
for mut ind in 0..rmslice.len() {
if (rmslice[ind] >> bit).into() & T::zero() == T::one() {
rmslice.swap(ind, last);
ind -= 1;
} else {
count += 1;
}
}
if bit > 0 {
unsigned_sort_at_bit(rmslice[0..count + 1], bit - 1);
unsigned_sort_at_bit(rmslice[count + 1..last + 1], bit - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment