Created
September 4, 2018 07:36
-
-
Save tenthree/6ea40702fa21654c4b93ff76f7d5d7ad 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
extern crate rand; | |
use rand::prelude::*; | |
fn main() { | |
const LEN: usize = 10; | |
let mut arr: [i32; LEN] = [0; LEN]; | |
let mut rng = thread_rng(); | |
for index in 0..LEN { | |
arr[index] = rng.gen_range(0, 101) | |
} | |
// before | |
println!("{:?}", &arr); | |
// insertion sort | |
for index in 0..LEN { | |
let tmp = arr[index]; | |
let mut cmp_index = index; | |
while cmp_index > 0 && arr[cmp_index - 1] > tmp { | |
arr[cmp_index] = arr[cmp_index - 1]; | |
cmp_index -= 1; | |
} | |
arr[cmp_index] = tmp; | |
} | |
// after | |
println!("{:?}", &arr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment