Advertisement
Guest User

Untitled

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