-
-
Save Dastagirireddy/fa2f29ddc6981ae85fa73b7b93efdf44 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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