|
| 1 | +pub fn quick_sort<T: Ord>(arr: &mut [T]) { |
| 2 | + let len = arr.len(); |
| 3 | + _quick_sort(arr, 0, (len - 1) as isize); |
| 4 | +} |
| 5 | + |
| 6 | +fn _quick_sort<T: Ord>(arr: &mut [T], low: isize, high: isize) { |
| 7 | + if low < high { |
| 8 | + let p = partition(arr, low, high); |
| 9 | + _quick_sort(arr, low, p - 1); |
| 10 | + _quick_sort(arr, p + 1, high); |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +fn partition<T: Ord>(arr: &mut [T], low: isize, high: isize) -> isize { |
| 15 | + let pivot = high as usize; |
| 16 | + let mut store_index = low - 1; |
| 17 | + let mut last_index = high; |
| 18 | + |
| 19 | + loop { |
| 20 | + store_index += 1; |
| 21 | + while arr[store_index as usize] < arr[pivot] { |
| 22 | + store_index += 1; |
| 23 | + } |
| 24 | + last_index -= 1; |
| 25 | + while last_index >= 0 && arr[last_index as usize] > arr[pivot] { |
| 26 | + last_index -= 1; |
| 27 | + } |
| 28 | + if store_index >= last_index { |
| 29 | + break; |
| 30 | + } else { |
| 31 | + arr.swap(store_index as usize, last_index as usize); |
| 32 | + } |
| 33 | + } |
| 34 | + arr.swap(store_index as usize, pivot as usize); |
| 35 | + store_index |
| 36 | +} |
| 37 | +fn main() { |
| 38 | + println!("Sort numbers ascending"); |
| 39 | + let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; |
| 40 | + println!("Before: {:?}", numbers); |
| 41 | + quick_sort(&mut numbers); |
| 42 | + println!("After: {:?}\n", numbers); |
| 43 | +} |
0 commit comments