3 //! This module contains a sorting algorithm based on Orson Peters' pattern-defeating quicksort,
4 //! published at: <https://github.com/orlp/pdqsort>
6 //! Unstable sorting is compatible with libcore because it doesn't allocate memory, unlike our
7 //! stable sorting implementation.
10 use crate::mem::{self, MaybeUninit, SizedTypeProperties};
13 /// When dropped, copies from `src` into `dest`.
14 struct CopyOnDrop<T> {
19 impl<T> Drop for CopyOnDrop<T> {
21 // SAFETY: This is a helper class.
22 // Please refer to its usage for correctness.
23 // Namely, one must be sure that `src` and `dst` does not overlap as required by `ptr::copy_nonoverlapping`.
25 ptr::copy_nonoverlapping(self.src, self.dest, 1);
30 /// Shifts the first element to the right until it encounters a greater or equal element.
31 fn shift_head<T, F>(v: &mut [T], is_less: &mut F)
33 F: FnMut(&T, &T) -> bool,
36 // SAFETY: The unsafe operations below involves indexing without a bounds check (by offsetting a
37 // pointer) and copying memory (`ptr::copy_nonoverlapping`).
40 // 1. We checked the size of the array to >=2.
41 // 2. All the indexing that we will do is always between {0 <= index < len} at most.
44 // 1. We are obtaining pointers to references which are guaranteed to be valid.
45 // 2. They cannot overlap because we obtain pointers to difference indices of the slice.
46 // Namely, `i` and `i-1`.
47 // 3. If the slice is properly aligned, the elements are properly aligned.
48 // It is the caller's responsibility to make sure the slice is properly aligned.
50 // See comments below for further detail.
52 // If the first two elements are out-of-order...
53 if len >= 2 && is_less(v.get_unchecked(1), v.get_unchecked(0)) {
54 // Read the first element into a stack-allocated variable. If a following comparison
55 // operation panics, `hole` will get dropped and automatically write the element back
57 let tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(0)));
58 let v = v.as_mut_ptr();
59 let mut hole = CopyOnDrop { src: &*tmp, dest: v.add(1) };
60 ptr::copy_nonoverlapping(v.add(1), v.add(0), 1);
63 if !is_less(&*v.add(i), &*tmp) {
67 // Move `i`-th element one place to the left, thus shifting the hole to the right.
68 ptr::copy_nonoverlapping(v.add(i), v.add(i - 1), 1);
71 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
76 /// Shifts the last element to the left until it encounters a smaller or equal element.
77 fn shift_tail<T, F>(v: &mut [T], is_less: &mut F)
79 F: FnMut(&T, &T) -> bool,
82 // SAFETY: The unsafe operations below involves indexing without a bound check (by offsetting a
83 // pointer) and copying memory (`ptr::copy_nonoverlapping`).
86 // 1. We checked the size of the array to >= 2.
87 // 2. All the indexing that we will do is always between `0 <= index < len-1` at most.
90 // 1. We are obtaining pointers to references which are guaranteed to be valid.
91 // 2. They cannot overlap because we obtain pointers to difference indices of the slice.
92 // Namely, `i` and `i+1`.
93 // 3. If the slice is properly aligned, the elements are properly aligned.
94 // It is the caller's responsibility to make sure the slice is properly aligned.
96 // See comments below for further detail.
98 // If the last two elements are out-of-order...
99 if len >= 2 && is_less(v.get_unchecked(len - 1), v.get_unchecked(len - 2)) {
100 // Read the last element into a stack-allocated variable. If a following comparison
101 // operation panics, `hole` will get dropped and automatically write the element back
103 let tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(len - 1)));
104 let v = v.as_mut_ptr();
105 let mut hole = CopyOnDrop { src: &*tmp, dest: v.add(len - 2) };
106 ptr::copy_nonoverlapping(v.add(len - 2), v.add(len - 1), 1);
108 for i in (0..len - 2).rev() {
109 if !is_less(&*tmp, &*v.add(i)) {
113 // Move `i`-th element one place to the right, thus shifting the hole to the left.
114 ptr::copy_nonoverlapping(v.add(i), v.add(i + 1), 1);
115 hole.dest = v.add(i);
117 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
122 /// Partially sorts a slice by shifting several out-of-order elements around.
124 /// Returns `true` if the slice is sorted at the end. This function is *O*(*n*) worst-case.
126 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
128 F: FnMut(&T, &T) -> bool,
130 // Maximum number of adjacent out-of-order pairs that will get shifted.
131 const MAX_STEPS: usize = 5;
132 // If the slice is shorter than this, don't shift any elements.
133 const SHORTEST_SHIFTING: usize = 50;
138 for _ in 0..MAX_STEPS {
139 // SAFETY: We already explicitly did the bound checking with `i < len`.
140 // All our subsequent indexing is only in the range `0 <= index < len`
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)) {
153 // Don't shift elements on short arrays, that has a performance cost.
154 if len < SHORTEST_SHIFTING {
158 // Swap the found pair of elements. This puts them in correct order.
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);
167 // Didn't manage to sort the slice in the limited number of steps.
171 /// Sorts a slice using insertion sort, which is *O*(*n*^2) worst-case.
172 fn insertion_sort<T, F>(v: &mut [T], is_less: &mut F)
174 F: FnMut(&T, &T) -> bool,
176 for i in 1..v.len() {
177 shift_tail(&mut v[..i + 1], is_less);
181 /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case.
183 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
184 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
186 F: FnMut(&T, &T) -> bool,
188 // This binary heap respects the invariant `parent >= child`.
189 let mut sift_down = |v: &mut [T], mut node| {
191 // Children of `node`.
192 let mut child = 2 * node + 1;
193 if child >= v.len() {
197 // Choose the greater child.
198 if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
202 // Stop if the invariant holds at `node`.
203 if !is_less(&v[node], &v[child]) {
207 // Swap `node` with the greater child, move one step down, and continue sifting.
213 // Build the heap in linear time.
214 for i in (0..v.len() / 2).rev() {
218 // Pop maximal elements from the heap.
219 for i in (1..v.len()).rev() {
221 sift_down(&mut v[..i], 0);
225 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
228 /// Returns the number of elements smaller than `pivot`.
230 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
231 /// This idea is presented in the [BlockQuicksort][pdf] paper.
233 /// [pdf]: https://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
234 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
236 F: FnMut(&T, &T) -> bool,
238 // Number of elements in a typical block.
239 const BLOCK: usize = 128;
241 // The partitioning algorithm repeats the following steps until completion:
243 // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
244 // 2. Trace a block from the right side to identify elements smaller than the pivot.
245 // 3. Exchange the identified elements between the left and right side.
247 // We keep the following variables for a block of elements:
249 // 1. `block` - Number of elements in the block.
250 // 2. `start` - Start pointer into the `offsets` array.
251 // 3. `end` - End pointer into the `offsets` array.
252 // 4. `offsets - Indices of out-of-order elements within the block.
254 // The current block on the left side (from `l` to `l.add(block_l)`).
255 let mut l = v.as_mut_ptr();
256 let mut block_l = BLOCK;
257 let mut start_l = ptr::null_mut();
258 let mut end_l = ptr::null_mut();
259 let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
261 // The current block on the right side (from `r.sub(block_r)` to `r`).
262 // SAFETY: The documentation for .add() specifically mention that `vec.as_ptr().add(vec.len())` is always safe`
263 let mut r = unsafe { l.add(v.len()) };
264 let mut block_r = BLOCK;
265 let mut start_r = ptr::null_mut();
266 let mut end_r = ptr::null_mut();
267 let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
269 // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
270 // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
272 // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
273 fn width<T>(l: *mut T, r: *mut T) -> usize {
274 assert!(mem::size_of::<T>() > 0);
275 // FIXME: this should *likely* use `offset_from`, but more
276 // investigation is needed (including running tests in miri).
277 (r.addr() - l.addr()) / mem::size_of::<T>()
281 // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
282 // some patch-up work in order to partition the remaining elements in between.
283 let is_done = width(l, r) <= 2 * BLOCK;
286 // Number of remaining elements (still not compared to the pivot).
287 let mut rem = width(l, r);
288 if start_l < end_l || start_r < end_r {
292 // Adjust block sizes so that the left and right block don't overlap, but get perfectly
293 // aligned to cover the whole remaining gap.
296 } else if start_r < end_r {
299 // There were the same number of elements to switch on both blocks during the last
300 // iteration, so there are no remaining elements on either block. Cover the remaining
301 // items with roughly equally-sized blocks.
303 block_r = rem - block_l;
305 debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
306 debug_assert!(width(l, r) == block_l + block_r);
309 if start_l == end_l {
310 // Trace `block_l` elements from the left side.
311 start_l = MaybeUninit::slice_as_mut_ptr(&mut offsets_l);
315 for i in 0..block_l {
316 // SAFETY: The unsafety operations below involve the usage of the `offset`.
317 // According to the conditions required by the function, we satisfy them because:
318 // 1. `offsets_l` is stack-allocated, and thus considered separate allocated object.
319 // 2. The function `is_less` returns a `bool`.
320 // Casting a `bool` will never overflow `isize`.
321 // 3. We have guaranteed that `block_l` will be `<= BLOCK`.
322 // Plus, `end_l` was initially set to the begin pointer of `offsets_` which was declared on the stack.
323 // Thus, we know that even in the worst case (all invocations of `is_less` returns false) we will only be at most 1 byte pass the end.
324 // Another unsafety operation here is dereferencing `elem`.
325 // However, `elem` was initially the begin pointer to the slice which is always valid.
327 // Branchless comparison.
329 end_l = end_l.add(!is_less(&*elem, pivot) as usize);
335 if start_r == end_r {
336 // Trace `block_r` elements from the right side.
337 start_r = MaybeUninit::slice_as_mut_ptr(&mut offsets_r);
341 for i in 0..block_r {
342 // SAFETY: The unsafety operations below involve the usage of the `offset`.
343 // According to the conditions required by the function, we satisfy them because:
344 // 1. `offsets_r` is stack-allocated, and thus considered separate allocated object.
345 // 2. The function `is_less` returns a `bool`.
346 // Casting a `bool` will never overflow `isize`.
347 // 3. We have guaranteed that `block_r` will be `<= BLOCK`.
348 // Plus, `end_r` was initially set to the begin pointer of `offsets_` which was declared on the stack.
349 // Thus, we know that even in the worst case (all invocations of `is_less` returns true) we will only be at most 1 byte pass the end.
350 // Another unsafety operation here is dereferencing `elem`.
351 // However, `elem` was initially `1 * sizeof(T)` past the end and we decrement it by `1 * sizeof(T)` before accessing it.
352 // Plus, `block_r` was asserted to be less than `BLOCK` and `elem` will therefore at most be pointing to the beginning of the slice.
354 // Branchless comparison.
357 end_r = end_r.add(is_less(&*elem, pivot) as usize);
362 // Number of out-of-order elements to swap between the left and right side.
363 let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
368 l.add(usize::from(*start_l))
373 r.sub(usize::from(*start_r) + 1)
377 // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
378 // permutation. This is not strictly equivalent to swapping, but produces a similar
379 // result using fewer memory operations.
381 // SAFETY: The use of `ptr::read` is valid because there is at least one element in
382 // both `offsets_l` and `offsets_r`, so `left!` is a valid pointer to read from.
384 // The uses of `left!` involve calls to `offset` on `l`, which points to the
385 // beginning of `v`. All the offsets pointed-to by `start_l` are at most `block_l`, so
386 // these `offset` calls are safe as all reads are within the block. The same argument
387 // applies for the uses of `right!`.
389 // The calls to `start_l.offset` are valid because there are at most `count-1` of them,
390 // plus the final one at the end of the unsafe block, where `count` is the minimum number
391 // of collected offsets in `offsets_l` and `offsets_r`, so there is no risk of there not
392 // being enough elements. The same reasoning applies to the calls to `start_r.offset`.
394 // The calls to `copy_nonoverlapping` are safe because `left!` and `right!` are guaranteed
395 // not to overlap, and are valid because of the reasoning above.
397 let tmp = ptr::read(left!());
398 ptr::copy_nonoverlapping(right!(), left!(), 1);
401 start_l = start_l.add(1);
402 ptr::copy_nonoverlapping(left!(), right!(), 1);
403 start_r = start_r.add(1);
404 ptr::copy_nonoverlapping(right!(), left!(), 1);
407 ptr::copy_nonoverlapping(&tmp, right!(), 1);
409 start_l = start_l.add(1);
410 start_r = start_r.add(1);
414 if start_l == end_l {
415 // All out-of-order elements in the left block were moved. Move to the next block.
417 // block-width-guarantee
418 // SAFETY: if `!is_done` then the slice width is guaranteed to be at least `2*BLOCK` wide. There
419 // are at most `BLOCK` elements in `offsets_l` because of its size, so the `offset` operation is
420 // safe. Otherwise, the debug assertions in the `is_done` case guarantee that
421 // `width(l, r) == block_l + block_r`, namely, that the block sizes have been adjusted to account
422 // for the smaller number of remaining elements.
423 l = unsafe { l.add(block_l) };
426 if start_r == end_r {
427 // All out-of-order elements in the right block were moved. Move to the previous block.
429 // SAFETY: Same argument as [block-width-guarantee]. Either this is a full block `2*BLOCK`-wide,
430 // or `block_r` has been adjusted for the last handful of elements.
431 r = unsafe { r.sub(block_r) };
439 // All that remains now is at most one block (either the left or the right) with out-of-order
440 // elements that need to be moved. Such remaining elements can be simply shifted to the end
441 // within their block.
444 // The left block remains.
445 // Move its remaining out-of-order elements to the far right.
446 debug_assert_eq!(width(l, r), block_l);
447 while start_l < end_l {
448 // remaining-elements-safety
449 // SAFETY: while the loop condition holds there are still elements in `offsets_l`, so it
450 // is safe to point `end_l` to the previous element.
452 // The `ptr::swap` is safe if both its arguments are valid for reads and writes:
453 // - Per the debug assert above, the distance between `l` and `r` is `block_l`
454 // elements, so there can be at most `block_l` remaining offsets between `start_l`
455 // and `end_l`. This means `r` will be moved at most `block_l` steps back, which
456 // makes the `r.offset` calls valid (at that point `l == r`).
457 // - `offsets_l` contains valid offsets into `v` collected during the partitioning of
458 // the last block, so the `l.offset` calls are valid.
460 end_l = end_l.sub(1);
461 ptr::swap(l.add(usize::from(*end_l)), r.sub(1));
465 width(v.as_mut_ptr(), r)
466 } else if start_r < end_r {
467 // The right block remains.
468 // Move its remaining out-of-order elements to the far left.
469 debug_assert_eq!(width(l, r), block_r);
470 while start_r < end_r {
471 // SAFETY: See the reasoning in [remaining-elements-safety].
473 end_r = end_r.sub(1);
474 ptr::swap(l, r.sub(usize::from(*end_r) + 1));
478 width(v.as_mut_ptr(), l)
480 // Nothing else to do, we're done.
481 width(v.as_mut_ptr(), l)
485 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
486 /// equal to `v[pivot]`.
488 /// Returns a tuple of:
490 /// 1. Number of elements smaller than `v[pivot]`.
491 /// 2. True if `v` was already partitioned.
492 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
494 F: FnMut(&T, &T) -> bool,
496 let (mid, was_partitioned) = {
497 // Place the pivot at the beginning of slice.
499 let (pivot, v) = v.split_at_mut(1);
500 let pivot = &mut pivot[0];
502 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
503 // operation panics, the pivot will be automatically written back into the slice.
505 // SAFETY: `pivot` is a reference to the first element of `v`, so `ptr::read` is safe.
506 let tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
507 let _pivot_guard = CopyOnDrop { src: &*tmp, dest: pivot };
510 // Find the first pair of out-of-order elements.
514 // SAFETY: The unsafety below involves indexing an array.
515 // For the first one: We already do the bounds checking here with `l < r`.
516 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
517 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
519 // Find the first element greater than or equal to the pivot.
520 while l < r && is_less(v.get_unchecked(l), pivot) {
524 // Find the last element smaller that the pivot.
525 while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
530 (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
532 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
533 // variable) back into the slice where it originally was. This step is critical in ensuring
537 // Place the pivot between the two partitions.
540 (mid, was_partitioned)
543 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
545 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
546 /// elements smaller than the pivot.
547 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
549 F: FnMut(&T, &T) -> bool,
551 // Place the pivot at the beginning of slice.
553 let (pivot, v) = v.split_at_mut(1);
554 let pivot = &mut pivot[0];
556 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
557 // operation panics, the pivot will be automatically written back into the slice.
558 // SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
559 let tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
560 let _pivot_guard = CopyOnDrop { src: &*tmp, dest: pivot };
563 // Now partition the slice.
567 // SAFETY: The unsafety below involves indexing an array.
568 // For the first one: We already do the bounds checking here with `l < r`.
569 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
570 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
572 // Find the first element greater than the pivot.
573 while l < r && !is_less(pivot, v.get_unchecked(l)) {
577 // Find the last element equal to the pivot.
578 while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
587 // Swap the found pair of out-of-order elements.
589 let ptr = v.as_mut_ptr();
590 ptr::swap(ptr.add(l), ptr.add(r));
595 // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
598 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
599 // back into the slice where it originally was. This step is critical in ensuring safety!
602 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
603 /// partitions in quicksort.
605 fn break_patterns<T>(v: &mut [T]) {
608 // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
609 let mut random = len as u32;
610 let mut gen_u32 = || {
611 random ^= random << 13;
612 random ^= random >> 17;
613 random ^= random << 5;
616 let mut gen_usize = || {
617 if usize::BITS <= 32 {
620 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
624 // Take random numbers modulo this number.
625 // The number fits into `usize` because `len` is not greater than `isize::MAX`.
626 let modulus = len.next_power_of_two();
628 // Some pivot candidates will be in the nearby of this index. Let's randomize them.
629 let pos = len / 4 * 2;
632 // Generate a random number modulo `len`. However, in order to avoid costly operations
633 // we first take it modulo a power of two, and then decrease by `len` until it fits
634 // into the range `[0, len - 1]`.
635 let mut other = gen_usize() & (modulus - 1);
637 // `other` is guaranteed to be less than `2 * len`.
642 v.swap(pos - 1 + i, other);
647 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
649 /// Elements in `v` might be reordered in the process.
650 fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
652 F: FnMut(&T, &T) -> bool,
654 // Minimum length to choose the median-of-medians method.
655 // Shorter slices use the simple median-of-three method.
656 const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
657 // Maximum number of swaps that can be performed in this function.
658 const MAX_SWAPS: usize = 4 * 3;
662 // Three indices near which we are going to choose a pivot.
663 let mut a = len / 4 * 1;
664 let mut b = len / 4 * 2;
665 let mut c = len / 4 * 3;
667 // Counts the total number of swaps we are about to perform while sorting indices.
671 // Swaps indices so that `v[a] <= v[b]`.
672 // SAFETY: `len >= 8` so there are at least two elements in the neighborhoods of
673 // `a`, `b` and `c`. This means the three calls to `sort_adjacent` result in
674 // corresponding calls to `sort3` with valid 3-item neighborhoods around each
675 // pointer, which in turn means the calls to `sort2` are done with valid
676 // references. Thus the `v.get_unchecked` calls are safe, as is the `ptr::swap`
678 let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
679 if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
685 // Swaps indices so that `v[a] <= v[b] <= v[c]`.
686 let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
692 if len >= SHORTEST_MEDIAN_OF_MEDIANS {
693 // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
694 let mut sort_adjacent = |a: &mut usize| {
696 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
699 // Find medians in the neighborhoods of `a`, `b`, and `c`.
700 sort_adjacent(&mut a);
701 sort_adjacent(&mut b);
702 sort_adjacent(&mut c);
705 // Find the median among `a`, `b`, and `c`.
706 sort3(&mut a, &mut b, &mut c);
709 if swaps < MAX_SWAPS {
712 // The maximum number of swaps was performed. Chances are the slice is descending or mostly
713 // descending, so reversing will probably help sort it faster.
719 /// Sorts `v` recursively.
721 /// If the slice had a predecessor in the original array, it is specified as `pred`.
723 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
724 /// this function will immediately switch to heapsort.
725 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
727 F: FnMut(&T, &T) -> bool,
729 // Slices of up to this length get sorted using insertion sort.
730 const MAX_INSERTION: usize = 20;
732 // True if the last partitioning was reasonably balanced.
733 let mut was_balanced = true;
734 // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
735 let mut was_partitioned = true;
740 // Very short slices get sorted using insertion sort.
741 if len <= MAX_INSERTION {
742 insertion_sort(v, is_less);
746 // If too many bad pivot choices were made, simply fall back to heapsort in order to
747 // guarantee `O(n * log(n))` worst-case.
749 heapsort(v, is_less);
753 // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
754 // some elements around. Hopefully we'll choose a better pivot this time.
760 // Choose a pivot and try guessing whether the slice is already sorted.
761 let (pivot, likely_sorted) = choose_pivot(v, is_less);
763 // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
764 // selection predicts the slice is likely already sorted...
765 if was_balanced && was_partitioned && likely_sorted {
766 // Try identifying several out-of-order elements and shifting them to correct
767 // positions. If the slice ends up being completely sorted, we're done.
768 if partial_insertion_sort(v, is_less) {
773 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
774 // slice. Partition the slice into elements equal to and elements greater than the pivot.
775 // This case is usually hit when the slice contains many duplicate elements.
776 if let Some(p) = pred {
777 if !is_less(p, &v[pivot]) {
778 let mid = partition_equal(v, pivot, is_less);
780 // Continue sorting elements greater than the pivot.
786 // Partition the slice.
787 let (mid, was_p) = partition(v, pivot, is_less);
788 was_balanced = cmp::min(mid, len - mid) >= len / 8;
789 was_partitioned = was_p;
791 // Split the slice into `left`, `pivot`, and `right`.
792 let (left, right) = v.split_at_mut(mid);
793 let (pivot, right) = right.split_at_mut(1);
794 let pivot = &pivot[0];
796 // Recurse into the shorter side only in order to minimize the total number of recursive
797 // calls and consume less stack space. Then just continue with the longer side (this is
798 // akin to tail recursion).
799 if left.len() < right.len() {
800 recurse(left, is_less, pred, limit);
804 recurse(right, is_less, Some(pivot), limit);
810 /// Sorts `v` using pattern-defeating quicksort, which is *O*(*n* \* log(*n*)) worst-case.
811 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
813 F: FnMut(&T, &T) -> bool,
815 // Sorting has no meaningful behavior on zero-sized types.
820 // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
821 let limit = usize::BITS - v.len().leading_zeros();
823 recurse(v, &mut is_less, None, limit);
826 fn partition_at_index_loop<'a, T, F>(
830 mut pred: Option<&'a T>,
832 F: FnMut(&T, &T) -> bool,
835 // For slices of up to this length it's probably faster to simply sort them.
836 const MAX_INSERTION: usize = 10;
837 if v.len() <= MAX_INSERTION {
838 insertion_sort(v, is_less);
843 let (pivot, _) = choose_pivot(v, is_less);
845 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
846 // slice. Partition the slice into elements equal to and elements greater than the pivot.
847 // This case is usually hit when the slice contains many duplicate elements.
848 if let Some(p) = pred {
849 if !is_less(p, &v[pivot]) {
850 let mid = partition_equal(v, pivot, is_less);
852 // If we've passed our index, then we're good.
857 // Otherwise, continue sorting elements greater than the pivot.
865 let (mid, _) = partition(v, pivot, is_less);
867 // Split the slice into `left`, `pivot`, and `right`.
868 let (left, right) = v.split_at_mut(mid);
869 let (pivot, right) = right.split_at_mut(1);
870 let pivot = &pivot[0];
874 index = index - mid - 1;
876 } else if mid > index {
879 // If mid == index, then we're done, since partition() guaranteed that all elements
880 // after mid are greater than or equal to mid.
886 pub fn partition_at_index<T, F>(
890 ) -> (&mut [T], &mut T, &mut [T])
892 F: FnMut(&T, &T) -> bool,
894 use cmp::Ordering::Greater;
895 use cmp::Ordering::Less;
897 if index >= v.len() {
898 panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
902 // Sorting has no meaningful behavior on zero-sized types. Do nothing.
903 } else if index == v.len() - 1 {
904 // Find max element and place it in the last position of the array. We're free to use
905 // `unwrap()` here because we know v must not be empty.
906 let (max_index, _) = v
909 .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
911 v.swap(max_index, index);
912 } else if index == 0 {
913 // Find min element and place it in the first position of the array. We're free to use
914 // `unwrap()` here because we know v must not be empty.
915 let (min_index, _) = v
918 .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
920 v.swap(min_index, index);
922 partition_at_index_loop(v, index, &mut is_less, None);
925 let (left, right) = v.split_at_mut(index);
926 let (pivot, right) = right.split_at_mut(1);
927 let pivot = &mut pivot[0];