Advertisement
cwchen

[Rust] Insertion Sort Demo

Aug 22nd, 2017
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.08 KB | None | 0 0
  1. // Call rand library
  2. extern crate rand;
  3.  
  4. use rand::Rng;
  5.  
  6. fn main() {
  7.     // Initialize variables
  8.     const SIZE: usize = 10;
  9.     let mut array: [i32; SIZE] = [0; SIZE];
  10.  
  11.     // Set array elements with random integers
  12.     for i in 0..SIZE {
  13.         array[i] = rand::thread_rng().gen_range(1, 100 + 1);
  14.     }
  15.  
  16.     // Print out unsorted array
  17.     print!("Before sort: ");
  18.     display_slice(&array);
  19.  
  20.     // Insertion sort.
  21.     // Modify the array in-place.
  22.     for i in 1..(array.len()) {
  23.         let x = array[i];  // Temp data
  24.         let mut j = i;
  25.         while j > 0 &&  array[j-1] > x {
  26.            array[j] = array[j-1];  // Move element one step
  27.            j -= 1;
  28.         }
  29.         array[j] = x;  // Put back temp data
  30.     }
  31.  
  32.     // Print out sorted array
  33.     print!("After sort: ");
  34.     display_slice(&array);
  35. }
  36.  
  37. // Function to print out array with arbitrary size
  38. fn display_slice(slice: &[i32]) {
  39.     for i in 0..slice.len() {
  40.         print!("{}", slice[i]);
  41.  
  42.         if i < slice.len() - 1 {
  43.             print!(", ");
  44.         }
  45.     }
  46.     println!("");
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement