I'm playing around with trying to create both maximally efficient and maximally idiomatic Rust implementations for the book, "Intro to Algorithms, Thomas H. Cormen et al" as a way to learn Rust for myself as well as a way to provide some learning resources for others. In implementing something simple like "Insertion Sort" I found myself needing to use "as" to cast between usize and isize in order to follow the example algorithm as closely as possible with that given in the book. My question is, is this sufficiently idiomatic?
I came up with a solution that uses "slice.swap" instead that seems more idiomatic, but, is less efficient. What's the opinion of the experts? Is there a more idiomatic, yet, also more efficient way to do this?
Here is the way using "as casts":
pub fn sort_slice_mut<T: Ord + Copy>(slice: &mut [T]) {
for j in 1..slice.len() {
let key = slice[j];
let mut i = (j - 1) as isize;
while i >= 0 && slice[i as usize] > key {
slice[(i + 1) as usize] = slice[i as usize];
i -= 1;
}
slice[(i + 1) as usize] = key;
}
}
Here is what I think is more idiomatic, but, slightly less efficient:
pub fn sort_slice_mut_2<T: Ord + Copy>(slice: &mut [T]) {
for j in 1..slice.len() {
for i in (0..j).rev() {
if slice[i] > slice[i + 1] {
slice.swap(i, i + 1);
}
}
}
}
Is there anything else I should be considering to make either of the above example even more idiomatic (without taking away the opportunity to actually implement the algorithm)?