1 //! Parallel quicksort.
2 //!
3 //! This implementation is copied verbatim from `std::slice::sort_unstable` and then parallelized.
4 //! The only difference from the original is that calls to `recurse` are executed in parallel using
5 //! `rayon_core::join`.
6 
7 use std::cmp;
8 use std::mem;
9 use std::ptr;
10 
11 /// When dropped, takes the value out of `Option` and writes it into `dest`.
12 ///
13 /// This allows us to safely read the pivot into a stack-allocated variable for efficiency, and
14 /// write it back into the slice after partitioning. This way we ensure that the write happens
15 /// even if `is_less` panics in the meantime.
16 struct WriteOnDrop<T> {
17     value: Option<T>,
18     dest: *mut T,
19 }
20 
21 impl<T> Drop for WriteOnDrop<T> {
drop(&mut self)22     fn drop(&mut self) {
23         unsafe {
24             ptr::write(self.dest, self.value.take().unwrap());
25         }
26     }
27 }
28 
29 /// Holds a value, but never drops it.
30 struct NoDrop<T> {
31     value: Option<T>,
32 }
33 
34 impl<T> Drop for NoDrop<T> {
drop(&mut self)35     fn drop(&mut self) {
36         mem::forget(self.value.take());
37     }
38 }
39 
40 /// When dropped, copies from `src` into `dest`.
41 struct CopyOnDrop<T> {
42     src: *mut T,
43     dest: *mut T,
44 }
45 
46 impl<T> Drop for CopyOnDrop<T> {
drop(&mut self)47     fn drop(&mut self) {
48         unsafe {
49             ptr::copy_nonoverlapping(self.src, self.dest, 1);
50         }
51     }
52 }
53 
54 /// Shifts the first element to the right until it encounters a greater or equal element.
shift_head<T, F>(v: &mut [T], is_less: &F) where F: Fn(&T, &T) -> bool,55 fn shift_head<T, F>(v: &mut [T], is_less: &F)
56 where
57     F: Fn(&T, &T) -> bool,
58 {
59     let len = v.len();
60     unsafe {
61         // If the first two elements are out-of-order...
62         if len >= 2 && is_less(v.get_unchecked(1), v.get_unchecked(0)) {
63             // Read the first element into a stack-allocated variable. If a following comparison
64             // operation panics, `hole` will get dropped and automatically write the element back
65             // into the slice.
66             let mut tmp = NoDrop {
67                 value: Some(ptr::read(v.get_unchecked(0))),
68             };
69             let mut hole = CopyOnDrop {
70                 src: tmp.value.as_mut().unwrap(),
71                 dest: v.get_unchecked_mut(1),
72             };
73             ptr::copy_nonoverlapping(v.get_unchecked(1), v.get_unchecked_mut(0), 1);
74 
75             for i in 2..len {
76                 if !is_less(v.get_unchecked(i), tmp.value.as_ref().unwrap()) {
77                     break;
78                 }
79 
80                 // Move `i`-th element one place to the left, thus shifting the hole to the right.
81                 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i - 1), 1);
82                 hole.dest = v.get_unchecked_mut(i);
83             }
84             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
85         }
86     }
87 }
88 
89 /// Shifts the last element to the left until it encounters a smaller or equal element.
shift_tail<T, F>(v: &mut [T], is_less: &F) where F: Fn(&T, &T) -> bool,90 fn shift_tail<T, F>(v: &mut [T], is_less: &F)
91 where
92     F: Fn(&T, &T) -> bool,
93 {
94     let len = v.len();
95     unsafe {
96         // If the last two elements are out-of-order...
97         if len >= 2 && is_less(v.get_unchecked(len - 1), v.get_unchecked(len - 2)) {
98             // Read the last element into a stack-allocated variable. If a following comparison
99             // operation panics, `hole` will get dropped and automatically write the element back
100             // into the slice.
101             let mut tmp = NoDrop {
102                 value: Some(ptr::read(v.get_unchecked(len - 1))),
103             };
104             let mut hole = CopyOnDrop {
105                 src: tmp.value.as_mut().unwrap(),
106                 dest: v.get_unchecked_mut(len - 2),
107             };
108             ptr::copy_nonoverlapping(v.get_unchecked(len - 2), v.get_unchecked_mut(len - 1), 1);
109 
110             for i in (0..len - 2).rev() {
111                 if !is_less(&tmp.value.as_ref().unwrap(), v.get_unchecked(i)) {
112                     break;
113                 }
114 
115                 // Move `i`-th element one place to the right, thus shifting the hole to the left.
116                 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i + 1), 1);
117                 hole.dest = v.get_unchecked_mut(i);
118             }
119             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
120         }
121     }
122 }
123 
124 /// Partially sorts a slice by shifting several out-of-order elements around.
125 ///
126 /// Returns `true` if the slice is sorted at the end. This function is `O(n)` worst-case.
127 #[cold]
partial_insertion_sort<T, F>(v: &mut [T], is_less: &F) -> bool where F: Fn(&T, &T) -> bool,128 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &F) -> bool
129 where
130     F: Fn(&T, &T) -> bool,
131 {
132     // Maximum number of adjacent out-of-order pairs that will get shifted.
133     const MAX_STEPS: usize = 5;
134     // If the slice is shorter than this, don't shift any elements.
135     const SHORTEST_SHIFTING: usize = 50;
136 
137     let len = v.len();
138     let mut i = 1;
139 
140     for _ in 0..MAX_STEPS {
141         unsafe {
142             // Find the next pair of adjacent out-of-order elements.
143             while i < len && !is_less(v.get_unchecked(i), v.get_unchecked(i - 1)) {
144                 i += 1;
145             }
146         }
147 
148         // Are we done?
149         if i == len {
150             return true;
151         }
152 
153         // Don't shift elements on short arrays, that has a performance cost.
154         if len < SHORTEST_SHIFTING {
155             return false;
156         }
157 
158         // Swap the found pair of elements. This puts them in correct order.
159         v.swap(i - 1, i);
160 
161         // Shift the smaller element to the left.
162         shift_tail(&mut v[..i], is_less);
163         // Shift the greater element to the right.
164         shift_head(&mut v[i..], is_less);
165     }
166 
167     // Didn't manage to sort the slice in the limited number of steps.
168     false
169 }
170 
171 /// Sorts a slice using insertion sort, which is `O(n^2)` worst-case.
insertion_sort<T, F>(v: &mut [T], is_less: &F) where F: Fn(&T, &T) -> bool,172 fn insertion_sort<T, F>(v: &mut [T], is_less: &F)
173 where
174     F: Fn(&T, &T) -> bool,
175 {
176     for i in 1..v.len() {
177         shift_tail(&mut v[..=i], is_less);
178     }
179 }
180 
181 /// Sorts `v` using heapsort, which guarantees `O(n log n)` worst-case.
182 #[cold]
heapsort<T, F>(v: &mut [T], is_less: &F) where F: Fn(&T, &T) -> bool,183 fn heapsort<T, F>(v: &mut [T], is_less: &F)
184 where
185     F: Fn(&T, &T) -> bool,
186 {
187     // This binary heap respects the invariant `parent >= child`.
188     let sift_down = |v: &mut [T], mut node| {
189         loop {
190             // Children of `node`:
191             let left = 2 * node + 1;
192             let right = 2 * node + 2;
193 
194             // Choose the greater child.
195             let greater = if right < v.len() && is_less(&v[left], &v[right]) {
196                 right
197             } else {
198                 left
199             };
200 
201             // Stop if the invariant holds at `node`.
202             if greater >= v.len() || !is_less(&v[node], &v[greater]) {
203                 break;
204             }
205 
206             // Swap `node` with the greater child, move one step down, and continue sifting.
207             v.swap(node, greater);
208             node = greater;
209         }
210     };
211 
212     // Build the heap in linear time.
213     for i in (0..v.len() / 2).rev() {
214         sift_down(v, i);
215     }
216 
217     // Pop maximal elements from the heap.
218     for i in (1..v.len()).rev() {
219         v.swap(0, i);
220         sift_down(&mut v[..i], 0);
221     }
222 }
223 
224 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
225 /// to `pivot`.
226 ///
227 /// Returns the number of elements smaller than `pivot`.
228 ///
229 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
230 /// This idea is presented in the [BlockQuicksort][pdf] paper.
231 ///
232 /// [pdf]: http://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &F) -> usize where F: Fn(&T, &T) -> bool,233 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &F) -> usize
234 where
235     F: Fn(&T, &T) -> bool,
236 {
237     // Number of elements in a typical block.
238     const BLOCK: usize = 128;
239 
240     // The partitioning algorithm repeats the following steps until completion:
241     //
242     // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
243     // 2. Trace a block from the right side to identify elements smaller than the pivot.
244     // 3. Exchange the identified elements between the left and right side.
245     //
246     // We keep the following variables for a block of elements:
247     //
248     // 1. `block` - Number of elements in the block.
249     // 2. `start` - Start pointer into the `offsets` array.
250     // 3. `end` - End pointer into the `offsets` array.
251     // 4. `offsets - Indices of out-of-order elements within the block.
252 
253     // The current block on the left side (from `l` to `l.offset(block_l)`).
254     let mut l = v.as_mut_ptr();
255     let mut block_l = BLOCK;
256     let mut start_l = ptr::null_mut();
257     let mut end_l = ptr::null_mut();
258     let mut offsets_l = [0u8; BLOCK];
259 
260     // The current block on the right side (from `r.offset(-block_r)` to `r`).
261     let mut r = unsafe { l.add(v.len()) };
262     let mut block_r = BLOCK;
263     let mut start_r = ptr::null_mut();
264     let mut end_r = ptr::null_mut();
265     let mut offsets_r = [0u8; BLOCK];
266 
267     // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
268     fn width<T>(l: *mut T, r: *mut T) -> usize {
269         assert!(mem::size_of::<T>() > 0);
270         (r as usize - l as usize) / mem::size_of::<T>()
271     }
272 
273     loop {
274         // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
275         // some patch-up work in order to partition the remaining elements in between.
276         let is_done = width(l, r) <= 2 * BLOCK;
277 
278         if is_done {
279             // Number of remaining elements (still not compared to the pivot).
280             let mut rem = width(l, r);
281             if start_l < end_l || start_r < end_r {
282                 rem -= BLOCK;
283             }
284 
285             // Adjust block sizes so that the left and right block don't overlap, but get perfectly
286             // aligned to cover the whole remaining gap.
287             if start_l < end_l {
288                 block_r = rem;
289             } else if start_r < end_r {
290                 block_l = rem;
291             } else {
292                 block_l = rem / 2;
293                 block_r = rem - block_l;
294             }
295             debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
296             debug_assert!(width(l, r) == block_l + block_r);
297         }
298 
299         if start_l == end_l {
300             // Trace `block_l` elements from the left side.
301             start_l = offsets_l.as_mut_ptr();
302             end_l = offsets_l.as_mut_ptr();
303             let mut elem = l;
304 
305             for i in 0..block_l {
306                 unsafe {
307                     // Branchless comparison.
308                     *end_l = i as u8;
309                     end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
310                     elem = elem.offset(1);
311                 }
312             }
313         }
314 
315         if start_r == end_r {
316             // Trace `block_r` elements from the right side.
317             start_r = offsets_r.as_mut_ptr();
318             end_r = offsets_r.as_mut_ptr();
319             let mut elem = r;
320 
321             for i in 0..block_r {
322                 unsafe {
323                     // Branchless comparison.
324                     elem = elem.offset(-1);
325                     *end_r = i as u8;
326                     end_r = end_r.offset(is_less(&*elem, pivot) as isize);
327                 }
328             }
329         }
330 
331         // Number of out-of-order elements to swap between the left and right side.
332         let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
333 
334         if count > 0 {
335             macro_rules! left {
336                 () => {
337                     l.offset(*start_l as isize)
338                 };
339             }
340             macro_rules! right {
341                 () => {
342                     r.offset(-(*start_r as isize) - 1)
343                 };
344             }
345 
346             // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
347             // permutation. This is not strictly equivalent to swapping, but produces a similar
348             // result using fewer memory operations.
349             unsafe {
350                 let tmp = ptr::read(left!());
351                 ptr::copy_nonoverlapping(right!(), left!(), 1);
352 
353                 for _ in 1..count {
354                     start_l = start_l.offset(1);
355                     ptr::copy_nonoverlapping(left!(), right!(), 1);
356                     start_r = start_r.offset(1);
357                     ptr::copy_nonoverlapping(right!(), left!(), 1);
358                 }
359 
360                 ptr::copy_nonoverlapping(&tmp, right!(), 1);
361                 mem::forget(tmp);
362                 start_l = start_l.offset(1);
363                 start_r = start_r.offset(1);
364             }
365         }
366 
367         if start_l == end_l {
368             // All out-of-order elements in the left block were moved. Move to the next block.
369             l = unsafe { l.add(block_l) };
370         }
371 
372         if start_r == end_r {
373             // All out-of-order elements in the right block were moved. Move to the previous block.
374             r = unsafe { r.sub(block_r) };
375         }
376 
377         if is_done {
378             break;
379         }
380     }
381 
382     // All that remains now is at most one block (either the left or the right) with out-of-order
383     // elements that need to be moved. Such remaining elements can be simply shifted to the end
384     // within their block.
385 
386     if start_l < end_l {
387         // The left block remains.
388         // Move it's remaining out-of-order elements to the far right.
389         debug_assert_eq!(width(l, r), block_l);
390         while start_l < end_l {
391             unsafe {
392                 end_l = end_l.offset(-1);
393                 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
394                 r = r.offset(-1);
395             }
396         }
397         width(v.as_mut_ptr(), r)
398     } else if start_r < end_r {
399         // The right block remains.
400         // Move it's remaining out-of-order elements to the far left.
401         debug_assert_eq!(width(l, r), block_r);
402         while start_r < end_r {
403             unsafe {
404                 end_r = end_r.offset(-1);
405                 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
406                 l = l.offset(1);
407             }
408         }
409         width(v.as_mut_ptr(), l)
410     } else {
411         // Nothing else to do, we're done.
412         width(v.as_mut_ptr(), l)
413     }
414 }
415 
416 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
417 /// equal to `v[pivot]`.
418 ///
419 /// Returns a tuple of:
420 ///
421 /// 1. Number of elements smaller than `v[pivot]`.
422 /// 2. True if `v` was already partitioned.
partition<T, F>(v: &mut [T], pivot: usize, is_less: &F) -> (usize, bool) where F: Fn(&T, &T) -> bool,423 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &F) -> (usize, bool)
424 where
425     F: Fn(&T, &T) -> bool,
426 {
427     let (mid, was_partitioned) = {
428         // Place the pivot at the beginning of slice.
429         v.swap(0, pivot);
430         let (pivot, v) = v.split_at_mut(1);
431         let pivot = &mut pivot[0];
432 
433         // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
434         // operation panics, the pivot will be automatically written back into the slice.
435         let write_on_drop = WriteOnDrop {
436             value: unsafe { Some(ptr::read(pivot)) },
437             dest: pivot,
438         };
439         let pivot = write_on_drop.value.as_ref().unwrap();
440 
441         // Find the first pair of out-of-order elements.
442         let mut l = 0;
443         let mut r = v.len();
444         unsafe {
445             // Find the first element greater then or equal to the pivot.
446             while l < r && is_less(v.get_unchecked(l), pivot) {
447                 l += 1;
448             }
449 
450             // Find the last element smaller that the pivot.
451             while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
452                 r -= 1;
453             }
454         }
455 
456         (
457             l + partition_in_blocks(&mut v[l..r], pivot, is_less),
458             l >= r,
459         )
460 
461         // `write_on_drop` goes out of scope and writes the pivot (which is a stack-allocated
462         // variable) back into the slice where it originally was. This step is critical in ensuring
463         // safety!
464     };
465 
466     // Place the pivot between the two partitions.
467     v.swap(0, mid);
468 
469     (mid, was_partitioned)
470 }
471 
472 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
473 ///
474 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
475 /// elements smaller than the pivot.
partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &F) -> usize where F: Fn(&T, &T) -> bool,476 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &F) -> usize
477 where
478     F: Fn(&T, &T) -> bool,
479 {
480     // Place the pivot at the beginning of slice.
481     v.swap(0, pivot);
482     let (pivot, v) = v.split_at_mut(1);
483     let pivot = &mut pivot[0];
484 
485     // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
486     // operation panics, the pivot will be automatically written back into the slice.
487     let write_on_drop = WriteOnDrop {
488         value: unsafe { Some(ptr::read(pivot)) },
489         dest: pivot,
490     };
491     let pivot = write_on_drop.value.as_ref().unwrap();
492 
493     // Now partition the slice.
494     let mut l = 0;
495     let mut r = v.len();
496     loop {
497         unsafe {
498             // Find the first element greater that the pivot.
499             while l < r && !is_less(pivot, v.get_unchecked(l)) {
500                 l += 1;
501             }
502 
503             // Find the last element equal to the pivot.
504             while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
505                 r -= 1;
506             }
507 
508             // Are we done?
509             if l >= r {
510                 break;
511             }
512 
513             // Swap the found pair of out-of-order elements.
514             r -= 1;
515             ptr::swap(v.get_unchecked_mut(l), v.get_unchecked_mut(r));
516             l += 1;
517         }
518     }
519 
520     // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
521     l + 1
522 
523     // `write_on_drop` goes out of scope and writes the pivot (which is a stack-allocated variable)
524     // back into the slice where it originally was. This step is critical in ensuring safety!
525 }
526 
527 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
528 /// partitions in quicksort.
529 #[cold]
break_patterns<T>(v: &mut [T])530 fn break_patterns<T>(v: &mut [T]) {
531     let len = v.len();
532     if len >= 8 {
533         // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
534         let mut random = len as u32;
535         let mut gen_u32 = || {
536             random ^= random << 13;
537             random ^= random >> 17;
538             random ^= random << 5;
539             random
540         };
541         let mut gen_usize = || {
542             if mem::size_of::<usize>() <= 4 {
543                 gen_u32() as usize
544             } else {
545                 ((u64::from(gen_u32()) << 32) | u64::from(gen_u32())) as usize
546             }
547         };
548 
549         // Take random numbers modulo this number.
550         // The number fits into `usize` because `len` is not greater than `isize::MAX`.
551         let modulus = len.next_power_of_two();
552 
553         // Some pivot candidates will be in the nearby of this index. Let's randomize them.
554         let pos = len / 4 * 2;
555 
556         for i in 0..3 {
557             // Generate a random number modulo `len`. However, in order to avoid costly operations
558             // we first take it modulo a power of two, and then decrease by `len` until it fits
559             // into the range `[0, len - 1]`.
560             let mut other = gen_usize() & (modulus - 1);
561 
562             // `other` is guaranteed to be less than `2 * len`.
563             if other >= len {
564                 other -= len;
565             }
566 
567             v.swap(pos - 1 + i, other);
568         }
569     }
570 }
571 
572 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
573 ///
574 /// Elements in `v` might be reordered in the process.
choose_pivot<T, F>(v: &mut [T], is_less: &F) -> (usize, bool) where F: Fn(&T, &T) -> bool,575 fn choose_pivot<T, F>(v: &mut [T], is_less: &F) -> (usize, bool)
576 where
577     F: Fn(&T, &T) -> bool,
578 {
579     // Minimum length to choose the median-of-medians method.
580     // Shorter slices use the simple median-of-three method.
581     const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
582     // Maximum number of swaps that can be performed in this function.
583     const MAX_SWAPS: usize = 4 * 3;
584 
585     let len = v.len();
586 
587     // Three indices near which we are going to choose a pivot.
588     let mut a = len / 4 * 1;
589     let mut b = len / 4 * 2;
590     let mut c = len / 4 * 3;
591 
592     // Counts the total number of swaps we are about to perform while sorting indices.
593     let mut swaps = 0;
594 
595     if len >= 8 {
596         // Swaps indices so that `v[a] <= v[b]`.
597         let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
598             if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
599                 ptr::swap(a, b);
600                 swaps += 1;
601             }
602         };
603 
604         // Swaps indices so that `v[a] <= v[b] <= v[c]`.
605         let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
606             sort2(a, b);
607             sort2(b, c);
608             sort2(a, b);
609         };
610 
611         if len >= SHORTEST_MEDIAN_OF_MEDIANS {
612             // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
613             let mut sort_adjacent = |a: &mut usize| {
614                 let tmp = *a;
615                 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
616             };
617 
618             // Find medians in the neighborhoods of `a`, `b`, and `c`.
619             sort_adjacent(&mut a);
620             sort_adjacent(&mut b);
621             sort_adjacent(&mut c);
622         }
623 
624         // Find the median among `a`, `b`, and `c`.
625         sort3(&mut a, &mut b, &mut c);
626     }
627 
628     if swaps < MAX_SWAPS {
629         (b, swaps == 0)
630     } else {
631         // The maximum number of swaps was performed. Chances are the slice is descending or mostly
632         // descending, so reversing will probably help sort it faster.
633         v.reverse();
634         (len - 1 - b, true)
635     }
636 }
637 
638 /// Sorts `v` recursively.
639 ///
640 /// If the slice had a predecessor in the original array, it is specified as `pred`.
641 ///
642 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
643 /// this function will immediately switch to heapsort.
recurse<'a, T, F>(mut v: &'a mut [T], is_less: &F, mut pred: Option<&'a mut T>, mut limit: usize) where T: Send, F: Fn(&T, &T) -> bool + Sync,644 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &F, mut pred: Option<&'a mut T>, mut limit: usize)
645 where
646     T: Send,
647     F: Fn(&T, &T) -> bool + Sync,
648 {
649     // Slices of up to this length get sorted using insertion sort.
650     const MAX_INSERTION: usize = 20;
651     // If both partitions are up to this length, we continue sequentially. This number is as small
652     // as possible but so that the overhead of Rayon's task scheduling is still negligible.
653     const MAX_SEQUENTIAL: usize = 2000;
654 
655     // True if the last partitioning was reasonably balanced.
656     let mut was_balanced = true;
657     // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
658     let mut was_partitioned = true;
659 
660     loop {
661         let len = v.len();
662 
663         // Very short slices get sorted using insertion sort.
664         if len <= MAX_INSERTION {
665             insertion_sort(v, is_less);
666             return;
667         }
668 
669         // If too many bad pivot choices were made, simply fall back to heapsort in order to
670         // guarantee `O(n log n)` worst-case.
671         if limit == 0 {
672             heapsort(v, is_less);
673             return;
674         }
675 
676         // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
677         // some elements around. Hopefully we'll choose a better pivot this time.
678         if !was_balanced {
679             break_patterns(v);
680             limit -= 1;
681         }
682 
683         // Choose a pivot and try guessing whether the slice is already sorted.
684         let (pivot, likely_sorted) = choose_pivot(v, is_less);
685 
686         // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
687         // selection predicts the slice is likely already sorted...
688         if was_balanced && was_partitioned && likely_sorted {
689             // Try identifying several out-of-order elements and shifting them to correct
690             // positions. If the slice ends up being completely sorted, we're done.
691             if partial_insertion_sort(v, is_less) {
692                 return;
693             }
694         }
695 
696         // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
697         // slice. Partition the slice into elements equal to and elements greater than the pivot.
698         // This case is usually hit when the slice contains many duplicate elements.
699         if let Some(ref p) = pred {
700             if !is_less(p, &v[pivot]) {
701                 let mid = partition_equal(v, pivot, is_less);
702 
703                 // Continue sorting elements greater than the pivot.
704                 v = &mut { v }[mid..];
705                 continue;
706             }
707         }
708 
709         // Partition the slice.
710         let (mid, was_p) = partition(v, pivot, is_less);
711         was_balanced = cmp::min(mid, len - mid) >= len / 8;
712         was_partitioned = was_p;
713 
714         // Split the slice into `left`, `pivot`, and `right`.
715         let (left, right) = { v }.split_at_mut(mid);
716         let (pivot, right) = right.split_at_mut(1);
717         let pivot = &mut pivot[0];
718 
719         if cmp::max(left.len(), right.len()) <= MAX_SEQUENTIAL {
720             // Recurse into the shorter side only in order to minimize the total number of recursive
721             // calls and consume less stack space. Then just continue with the longer side (this is
722             // akin to tail recursion).
723             if left.len() < right.len() {
724                 recurse(left, is_less, pred, limit);
725                 v = right;
726                 pred = Some(pivot);
727             } else {
728                 recurse(right, is_less, Some(pivot), limit);
729                 v = left;
730             }
731         } else {
732             // Sort the left and right half in parallel.
733             rayon_core::join(
734                 || recurse(left, is_less, pred, limit),
735                 || recurse(right, is_less, Some(pivot), limit),
736             );
737             break;
738         }
739     }
740 }
741 
742 /// Sorts `v` using pattern-defeating quicksort in parallel.
743 ///
744 /// The algorithm is unstable, in-place, and `O(n log n)` worst-case.
par_quicksort<T, F>(v: &mut [T], is_less: F) where T: Send, F: Fn(&T, &T) -> bool + Sync,745 pub(super) fn par_quicksort<T, F>(v: &mut [T], is_less: F)
746 where
747     T: Send,
748     F: Fn(&T, &T) -> bool + Sync,
749 {
750     // Sorting has no meaningful behavior on zero-sized types.
751     if mem::size_of::<T>() == 0 {
752         return;
753     }
754 
755     // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
756     let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
757 
758     recurse(v, &is_less, None, limit);
759 }
760 
761 #[cfg(test)]
762 mod tests {
763     use super::heapsort;
764     use rand::distributions::Uniform;
765     use rand::{thread_rng, Rng};
766 
767     #[test]
test_heapsort()768     fn test_heapsort() {
769         let rng = thread_rng();
770 
771         for len in (0..25).chain(500..501) {
772             for &modulus in &[5, 10, 100] {
773                 let dist = Uniform::new(0, modulus);
774                 for _ in 0..100 {
775                     let v: Vec<i32> = rng.sample_iter(&dist).take(len).collect();
776 
777                     // Test heapsort using `<` operator.
778                     let mut tmp = v.clone();
779                     heapsort(&mut tmp, &|a, b| a < b);
780                     assert!(tmp.windows(2).all(|w| w[0] <= w[1]));
781 
782                     // Test heapsort using `>` operator.
783                     let mut tmp = v.clone();
784                     heapsort(&mut tmp, &|a, b| a > b);
785                     assert!(tmp.windows(2).all(|w| w[0] >= w[1]));
786                 }
787             }
788         }
789 
790         // Sort using a completely random comparison function.
791         // This will reorder the elements *somehow*, but won't panic.
792         let mut v: Vec<_> = (0..100).collect();
793         heapsort(&mut v, &|_, _| thread_rng().gen());
794         heapsort(&mut v, &|a, b| a < b);
795 
796         for i in 0..v.len() {
797             assert_eq!(v[i], i);
798         }
799     }
800 }
801