Skip to content

Instantly share code, notes, and snippets.

@fschutt
Created January 1, 2018 00:32
Show Gist options
  • Save fschutt/db0228de32905a56b8145d22c11b4a74 to your computer and use it in GitHub Desktop.
Save fschutt/db0228de32905a56b8145d22c11b4a74 to your computer and use it in GitHub Desktop.
Insertion sort in Rust
fn insertion_sort(data: &mut Vec<u8>) {
if data.len() < 2 { return; /* already sorted */ }
for j in 1..data.len() {
let key = data[j];
let mut i = (j as i8) - 1;
while i >= 0 && data[i as usize] > key {
data[(i + 1) as usize] = data[i as usize];
i -= 1;
}
data[(i + 1) as usize] = key;
}
}
fn main() {
let mut data = vec![5, 2, 4, 6, 1, 3];
insertion_sort_reverse(&mut data);
println!("{:?}", data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment