Created
January 1, 2018 00:32
-
-
Save fschutt/db0228de32905a56b8145d22c11b4a74 to your computer and use it in GitHub Desktop.
Insertion sort in Rust
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
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