Skip to main content

lib_jsl_sorting/
quicksort.rs

1//! Quicksort.
2//!
3//! See the book entry [Comparison sorting](https://jwkunz.github.io/lib_jsl/book/sorting/comparison-sorts.html#quicksort).
4
5use crate::heapsort::heapsort;
6
7/// Sorts a slice using quicksort: a median-of-three pivot, Hoare's partition (whose two scans
8/// both stop at keys equal to the pivot, so runs of equal keys are split evenly rather than piling
9/// up on one side), insertion sort for ranges of 16 or fewer, and recursion on the smaller side so
10/// the stack depth is `O(log n)`. As in Musser's introsort, a range still unsorted after
11/// `2 log₂ n` partitions is finished by heapsort, so the worst case is `O(n log n)` even on
12/// inputs built to defeat median-of-three.
13pub fn quicksort<T: Ord>(slice: &mut [T]) {
14    let depth = 2 * (usize::BITS - slice.len().leading_zeros()) as usize;
15    introsort(slice, depth);
16}
17
18// ANCHOR: introsort
19fn introsort<T: Ord>(slice: &mut [T], mut depth: usize) {
20    let mut slice = slice;
21    loop {
22        if slice.len() <= 16 {
23            insertion_sort(slice);
24            return;
25        }
26        if depth == 0 {
27            // Too many unbalanced partitions: the pivots are being chosen badly.
28            heapsort(slice);
29            return;
30        }
31        depth -= 1;
32        let p = partition(slice);
33        let (left, rest) = slice.split_at_mut(p);
34        let right = &mut rest[1..];
35        if left.len() < right.len() {
36            introsort(left, depth);
37            slice = right;
38        } else {
39            introsort(right, depth);
40            slice = left;
41        }
42    }
43}
44// ANCHOR_END: introsort
45
46fn insertion_sort<T: Ord>(s: &mut [T]) {
47    for i in 1..s.len() {
48        let mut j = i;
49        while j > 0 && s[j - 1] > s[j] {
50            s.swap(j - 1, j);
51            j -= 1;
52        }
53    }
54}
55
56// ANCHOR: partition
57/// Hoare's partition around a median-of-three pivot; returns the pivot's final index, with
58/// smaller-or-equal keys before it and greater-or-equal keys after.
59fn partition<T: Ord>(s: &mut [T]) -> usize {
60    let last = s.len() - 1;
61    let mid = last / 2;
62    if s[mid] < s[0] {
63        s.swap(mid, 0);
64    }
65    if s[last] < s[0] {
66        s.swap(last, 0);
67    }
68    if s[last] < s[mid] {
69        s.swap(last, mid);
70    }
71    // Now s[0] <= s[mid] <= s[last]. The median becomes the pivot at index 0, where it stops the
72    // right-to-left scan, and s[last] >= pivot stops the left-to-right one.
73    s.swap(0, mid);
74    let (mut i, mut j) = (0, s.len());
75    loop {
76        i += 1;
77        while s[i] < s[0] {
78            i += 1;
79        }
80        j -= 1;
81        while s[0] < s[j] {
82            j -= 1;
83        }
84        if i >= j {
85            break;
86        }
87        s.swap(i, j);
88    }
89    s.swap(0, j);
90    j
91}
92// ANCHOR_END: partition
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn sorts_various() {
100        let mut v: Vec<i32> = (0..1000).map(|i| (i * 7919) % 1009 - 500).collect();
101        let mut expected = v.clone();
102        expected.sort();
103        quicksort(&mut v);
104        assert_eq!(v, expected);
105    }
106
107    #[test]
108    fn equal_keys_and_presorted_input_stay_fast() {
109        // A partition that sends every key equal to the pivot to one side takes quadratic time on
110        // these, and one that rearranges the greater keys can do so on sorted input.
111        let mut same = vec![7u8; 200_000];
112        quicksort(&mut same);
113        assert!(same.iter().all(|&x| x == 7));
114        let mut few: Vec<u32> = (0..200_000u32).map(|i| i.wrapping_mul(2_654_435_761) % 3).collect();
115        let mut expected = few.clone();
116        expected.sort();
117        quicksort(&mut few);
118        assert_eq!(few, expected);
119        let mut organ: Vec<u32> = (0..200_000u32).map(|i| i.min(200_000 - i)).collect();
120        let mut expected = organ.clone();
121        expected.sort();
122        quicksort(&mut organ);
123        assert_eq!(organ, expected);
124        let mut sorted: Vec<u32> = (0..200_000).collect();
125        quicksort(&mut sorted);
126        assert!(sorted.windows(2).all(|w| w[0] < w[1]));
127        let mut reversed: Vec<u32> = (0..200_000).rev().collect();
128        quicksort(&mut reversed);
129        assert_eq!(reversed, sorted);
130    }
131
132    /// McIlroy's adversary: keys start as "gas", larger than every value, and are frozen to
133    /// increasing values only when the sort compares two gas keys, choosing which one so as to
134    /// make the current pivot as bad as possible.
135    mod adversary {
136        use std::cell::RefCell;
137        use std::cmp::Ordering;
138        use std::rc::Rc;
139
140        pub struct State {
141            pub val: Vec<usize>,
142            gas: usize,
143            solid: usize,
144            candidate: usize,
145            pub comparisons: u64,
146        }
147
148        #[derive(Clone)]
149        pub struct Key {
150            pub i: usize,
151            pub state: Rc<RefCell<State>>,
152        }
153
154        pub fn keys(n: usize) -> (Vec<Key>, Rc<RefCell<State>>) {
155            let state = Rc::new(RefCell::new(State { val: vec![n; n], gas: n, solid: 0, candidate: 0, comparisons: 0 }));
156            ((0..n).map(|i| Key { i, state: state.clone() }).collect(), state)
157        }
158
159        impl PartialEq for Key {
160            fn eq(&self, other: &Self) -> bool {
161                self.cmp(other) == Ordering::Equal
162            }
163        }
164        impl Eq for Key {}
165        impl PartialOrd for Key {
166            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
167                Some(self.cmp(other))
168            }
169        }
170        impl Ord for Key {
171            fn cmp(&self, other: &Self) -> Ordering {
172                let mut s = self.state.borrow_mut();
173                s.comparisons += 1;
174                let (x, y, gas) = (self.i, other.i, s.gas);
175                if s.val[x] == gas && s.val[y] == gas {
176                    let frozen = if x == s.candidate { x } else { y };
177                    s.val[frozen] = s.solid;
178                    s.solid += 1;
179                }
180                if s.val[x] == gas {
181                    s.candidate = x;
182                } else if s.val[y] == gas {
183                    s.candidate = y;
184                }
185                s.val[x].cmp(&s.val[y])
186            }
187        }
188    }
189
190    #[test]
191    fn an_adversary_cannot_force_quadratic_time() {
192        // Without the heapsort fallback the adversary forced about n²/4 comparisons
193        // (16 million for n = 8000, 154 n log₂ n).
194        let n = 8000;
195        let (mut keys, state) = adversary::keys(n);
196        quicksort(&mut keys);
197        let comparisons = state.borrow().comparisons as f64;
198        assert!(comparisons < 8.0 * n as f64 * (n as f64).log2(), "{comparisons} comparisons");
199        let val = state.borrow().val.clone();
200        assert!(keys.windows(2).all(|w| val[w[0].i] <= val[w[1].i]));
201    }
202
203    #[test]
204    fn edge_cases() {
205        let mut e: Vec<i32> = vec![];
206        quicksort(&mut e);
207        let mut one = vec![1];
208        quicksort(&mut one);
209        let mut dup = vec![5; 100];
210        quicksort(&mut dup);
211        assert_eq!(dup, vec![5; 100]);
212        let mut asc: Vec<i32> = (0..500).collect();
213        quicksort(&mut asc);
214        assert!(asc.windows(2).all(|w| w[0] <= w[1]));
215        let mut desc: Vec<i32> = (0..500).rev().collect();
216        quicksort(&mut desc);
217        assert!(desc.windows(2).all(|w| w[0] <= w[1]));
218    }
219}