Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Call rand library
- extern crate rand;
- use rand::Rng;
- fn main() {
- // Initialize variables
- const SIZE: usize = 10;
- let mut array: [i32; SIZE] = [0; SIZE];
- // Set array elements with random integers
- for i in 0..SIZE {
- array[i] = rand::thread_rng().gen_range(1, 100 + 1);
- }
- // Print out unsorted array
- print!("Before sort: ");
- display_slice(&array);
- // Insertion sort.
- // Modify the array in-place.
- for i in 1..(array.len()) {
- let x = array[i]; // Temp data
- let mut j = i;
- while j > 0 && array[j-1] > x {
- array[j] = array[j-1]; // Move element one step
- j -= 1;
- }
- array[j] = x; // Put back temp data
- }
- // Print out sorted array
- print!("After sort: ");
- display_slice(&array);
- }
- // Function to print out array with arbitrary size
- fn display_slice(slice: &[i32]) {
- for i in 0..slice.len() {
- print!("{}", slice[i]);
- if i < slice.len() - 1 {
- print!(", ");
- }
- }
- println!("");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement