Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #![allow(dead_code)]
  2.  
  3. use rand::RngCore;
  4.  
  5. #[derive(Copy, Clone)]
  6. enum PivotChoice {
  7. Random,
  8. Last,
  9. }
  10.  
  11. fn main() {
  12. let mut numbers = [10, 8, 3, 6, 1, 4, 2, 5, 9, 7];
  13. let length = numbers.len();
  14. println!("{:?}", numbers);
  15. quick_sort(&mut numbers, 0, length, PivotChoice::Last);
  16. }
  17.  
  18. fn quick_sort(mut array: &mut [i32], from: usize, to: usize, pc: PivotChoice) {
  19. fn partition(array: &mut [i32], from: usize, pivot_idx: usize, to: usize)
  20. -> usize {
  21. let pivot = array[pivot_idx];
  22. let num_left = array[from..to].iter().filter(|n| **n <= pivot).count()-1;
  23. let new_pivot_idx = from + num_left;
  24. array.swap(pivot_idx, new_pivot_idx);
  25.  
  26. // l and r are indices for the left and right side respectively
  27. let mut r = to - 1;
  28. for l in from..new_pivot_idx {
  29. if array[l] > pivot {
  30. while array[r] > pivot {
  31. r -= 1;
  32. }
  33. array.swap(l, r);
  34. }
  35. }
  36.  
  37. new_pivot_idx
  38. }
  39.  
  40. if array[from..to].len() >= 2 {
  41. let pivot = match pc {
  42. PivotChoice::Random => rand::thread_rng().next_u32() as usize
  43. % (to - from) + from,
  44. PivotChoice::Last => to - 1,
  45. };
  46. let middle = partition(&mut array, from, pivot, to);
  47. print_progress(array, from, to);
  48. quick_sort(&mut array, from, middle, pc);
  49. quick_sort(&mut array, middle + 1, to, pc);
  50. }
  51. }
  52.  
  53. // Print array with the region [from..to] highlighted in LaTeX format.
  54. fn print_progress(array: &mut [i32], from: usize, to: usize) {
  55. print!("[");
  56. for i in 0..from {
  57. print!("{}, ", array[i]);
  58. }
  59. print!("\\textcolor{{red}}{{");
  60. for i in from..to {
  61. print!("{}, ", array[i]);
  62. }
  63. print!("}}");
  64. for i in to..array.len() {
  65. print!("{}, ", array[i]);
  66. }
  67. println!("]");
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement