Skip to content

Instantly share code, notes, and snippets.

@tenthree
Created September 4, 2018 07:36
Show Gist options
  • Save tenthree/6ea40702fa21654c4b93ff76f7d5d7ad to your computer and use it in GitHub Desktop.
Save tenthree/6ea40702fa21654c4b93ff76f7d5d7ad to your computer and use it in GitHub Desktop.
insertion sort in rust
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