SHARE
TWEET

Untitled

a guest Apr 24th, 2019 46 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fn main() {
  2.     let mut numbers = [10, 8, 3, 6, 1, 4, 2, 5, 9, 7];
  3.     let length = numbers.len();
  4.     println!("{:?}", numbers);
  5.     merge_sort(&mut numbers, 0, length);
  6. }
  7.  
  8. fn merge_sort(array: &mut [i32], from: usize, to: usize) {
  9.     fn merge(left: &[i32], right: &[i32]) -> Vec<i32> {
  10.         let mut merged = Vec::new();
  11.         let (mut l, mut r) = (0, 0);
  12.         while l < left.len() && r < right.len() {
  13.             if left[l] <= right[r] {
  14.                 merged.push(left[l]);
  15.                 l += 1;
  16.             } else {
  17.                 merged.push(right[r]);
  18.                 r += 1;
  19.             }
  20.         }
  21.         merged.extend_from_slice(&left[l..]);
  22.         merged.extend_from_slice(&right[r..]);
  23.         merged
  24.     }
  25.  
  26.     if array[from..to].len() > 1 {
  27.         let split_idx = (to+from) / 2;
  28.         merge_sort(array, from, split_idx);
  29.         merge_sort(array, split_idx, to);
  30.         let mut merged = merge(&array[from..split_idx], &array[split_idx..to]);
  31.         array[from..to].swap_with_slice(&mut merged);
  32.     }
  33.     print_progress(array, from, to);
  34. }
  35.  
  36. /// Print array with the region [from..to] highlighted in LaTeX format.
  37. fn print_progress(array: &mut [i32], from: usize, to: usize) {
  38.     print!("[");
  39.     for i in 0..from { print!("{}, ", array[i]); }
  40.     print!("\\textcolor{{red}}{{");
  41.     for i in from..to { print!("{}, ", array[i]); }
  42.     print!("}}");
  43.     for i in to..array.len() { print!("{}, ", array[i]); }
  44.     println!("]");
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top