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};
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 mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(0)));
58 let v = v.as_mut_ptr();
59 let mut hole = CopyOnDrop { src: &mut *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 mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(len - 1)));
104 let v = v.as_mut_ptr();
105 let mut hole = CopyOnDrop { src: &mut *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 left = 2 * node + 1;
193 let right = 2 * node + 2;
195 // Choose the greater child.
197 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
199 // Stop if the invariant holds at `node`.
200 if greater >= v.len() || !is_less(&v[node], &v[greater]) {
204 // Swap `node` with the greater child, move one step down, and continue sifting.
205 v.swap(node, greater);
210 // Build the heap in linear time.
211 for i in (0..v.len() / 2).rev() {
215 // Pop maximal elements from the heap.
216 for i in (1..v.len()).rev() {
218 sift_down(&mut v[..i], 0);
222 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
225 /// Returns the number of elements smaller than `pivot`.
227 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
228 /// This idea is presented in the [BlockQuicksort][pdf] paper.
230 /// [pdf]: https://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
231 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
233 F: FnMut(&T, &T) -> bool,
235 // Number of elements in a typical block.
236 const BLOCK: usize = 128;
238 // The partitioning algorithm repeats the following steps until completion:
240 // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
241 // 2. Trace a block from the right side to identify elements smaller than the pivot.
242 // 3. Exchange the identified elements between the left and right side.
244 // We keep the following variables for a block of elements:
246 // 1. `block` - Number of elements in the block.
247 // 2. `start` - Start pointer into the `offsets` array.
248 // 3. `end` - End pointer into the `offsets` array.
249 // 4. `offsets - Indices of out-of-order elements within the block.
251 // The current block on the left side (from `l` to `l.add(block_l)`).
252 let mut l = v.as_mut_ptr();
253 let mut block_l = BLOCK;
254 let mut start_l = ptr::null_mut();
255 let mut end_l = ptr::null_mut();
256 let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
258 // The current block on the right side (from `r.sub(block_r)` to `r`).
259 // SAFETY: The documentation for .add() specifically mention that `vec.as_ptr().add(vec.len())` is always safe`
260 let mut r = unsafe { l.add(v.len()) };
261 let mut block_r = BLOCK;
262 let mut start_r = ptr::null_mut();
263 let mut end_r = ptr::null_mut();
264 let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
266 // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
267 // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
269 // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
270 fn width<T>(l: *mut T, r: *mut T) -> usize {
271 assert!(mem::size_of::<T>() > 0);
272 (r as usize - l as usize) / mem::size_of::<T>()
276 // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
277 // some patch-up work in order to partition the remaining elements in between.
278 let is_done = width(l, r) <= 2 * BLOCK;
281 // Number of remaining elements (still not compared to the pivot).
282 let mut rem = width(l, r);
283 if start_l < end_l || start_r < end_r {
287 // Adjust block sizes so that the left and right block don't overlap, but get perfectly
288 // aligned to cover the whole remaining gap.
291 } else if start_r < end_r {
294 // There were the same number of elements to switch on both blocks during the last
295 // iteration, so there are no remaining elements on either block. Cover the remaining
296 // items with roughly equally-sized blocks.
298 block_r = rem - block_l;
300 debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
301 debug_assert!(width(l, r) == block_l + block_r);
304 if start_l == end_l {
305 // Trace `block_l` elements from the left side.
306 start_l = MaybeUninit::slice_as_mut_ptr(&mut offsets_l);
310 for i in 0..block_l {
311 // SAFETY: The unsafety operations below involve the usage of the `offset`.
312 // According to the conditions required by the function, we satisfy them because:
313 // 1. `offsets_l` is stack-allocated, and thus considered separate allocated object.
314 // 2. The function `is_less` returns a `bool`.
315 // Casting a `bool` will never overflow `isize`.
316 // 3. We have guaranteed that `block_l` will be `<= BLOCK`.
317 // Plus, `end_l` was initially set to the begin pointer of `offsets_` which was declared on the stack.
318 // 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.
319 // Another unsafety operation here is dereferencing `elem`.
320 // However, `elem` was initially the begin pointer to the slice which is always valid.
322 // Branchless comparison.
324 end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
325 elem = elem.offset(1);
330 if start_r == end_r {
331 // Trace `block_r` elements from the right side.
332 start_r = MaybeUninit::slice_as_mut_ptr(&mut offsets_r);
336 for i in 0..block_r {
337 // SAFETY: The unsafety operations below involve the usage of the `offset`.
338 // According to the conditions required by the function, we satisfy them because:
339 // 1. `offsets_r` is stack-allocated, and thus considered separate allocated object.
340 // 2. The function `is_less` returns a `bool`.
341 // Casting a `bool` will never overflow `isize`.
342 // 3. We have guaranteed that `block_r` will be `<= BLOCK`.
343 // Plus, `end_r` was initially set to the begin pointer of `offsets_` which was declared on the stack.
344 // 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.
345 // Another unsafety operation here is dereferencing `elem`.
346 // However, `elem` was initially `1 * sizeof(T)` past the end and we decrement it by `1 * sizeof(T)` before accessing it.
347 // Plus, `block_r` was asserted to be less than `BLOCK` and `elem` will therefore at most be pointing to the beginning of the slice.
349 // Branchless comparison.
350 elem = elem.offset(-1);
352 end_r = end_r.offset(is_less(&*elem, pivot) as isize);
357 // Number of out-of-order elements to swap between the left and right side.
358 let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
363 l.offset(*start_l as isize)
368 r.offset(-(*start_r as isize) - 1)
372 // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
373 // permutation. This is not strictly equivalent to swapping, but produces a similar
374 // result using fewer memory operations.
376 // SAFETY: The use of `ptr::read` is valid because there is at least one element in
377 // both `offsets_l` and `offsets_r`, so `left!` is a valid pointer to read from.
379 // The uses of `left!` involve calls to `offset` on `l`, which points to the
380 // beginning of `v`. All the offsets pointed-to by `start_l` are at most `block_l`, so
381 // these `offset` calls are safe as all reads are within the block. The same argument
382 // applies for the uses of `right!`.
384 // The calls to `start_l.offset` are valid because there are at most `count-1` of them,
385 // plus the final one at the end of the unsafe block, where `count` is the minimum number
386 // of collected offsets in `offsets_l` and `offsets_r`, so there is no risk of there not
387 // being enough elements. The same reasoning applies to the calls to `start_r.offset`.
389 // The calls to `copy_nonoverlapping` are safe because `left!` and `right!` are guaranteed
390 // not to overlap, and are valid because of the reasoning above.
392 let tmp = ptr::read(left!());
393 ptr::copy_nonoverlapping(right!(), left!(), 1);
396 start_l = start_l.offset(1);
397 ptr::copy_nonoverlapping(left!(), right!(), 1);
398 start_r = start_r.offset(1);
399 ptr::copy_nonoverlapping(right!(), left!(), 1);
402 ptr::copy_nonoverlapping(&tmp, right!(), 1);
404 start_l = start_l.offset(1);
405 start_r = start_r.offset(1);
409 if start_l == end_l {
410 // All out-of-order elements in the left block were moved. Move to the next block.
412 // block-width-guarantee
413 // SAFETY: if `!is_done` then the slice width is guaranteed to be at least `2*BLOCK` wide. There
414 // are at most `BLOCK` elements in `offsets_l` because of its size, so the `offset` operation is
415 // safe. Otherwise, the debug assertions in the `is_done` case guarantee that
416 // `width(l, r) == block_l + block_r`, namely, that the block sizes have been adjusted to account
417 // for the smaller number of remaining elements.
418 l = unsafe { l.offset(block_l as isize) };
421 if start_r == end_r {
422 // All out-of-order elements in the right block were moved. Move to the previous block.
424 // SAFETY: Same argument as [block-width-guarantee]. Either this is a full block `2*BLOCK`-wide,
425 // or `block_r` has been adjusted for the last handful of elements.
426 r = unsafe { r.offset(-(block_r as isize)) };
434 // All that remains now is at most one block (either the left or the right) with out-of-order
435 // elements that need to be moved. Such remaining elements can be simply shifted to the end
436 // within their block.
439 // The left block remains.
440 // Move its remaining out-of-order elements to the far right.
441 debug_assert_eq!(width(l, r), block_l);
442 while start_l < end_l {
443 // remaining-elements-safety
444 // SAFETY: while the loop condition holds there are still elements in `offsets_l`, so it
445 // is safe to point `end_l` to the previous element.
447 // The `ptr::swap` is safe if both its arguments are valid for reads and writes:
448 // - Per the debug assert above, the distance between `l` and `r` is `block_l`
449 // elements, so there can be at most `block_l` remaining offsets between `start_l`
450 // and `end_l`. This means `r` will be moved at most `block_l` steps back, which
451 // makes the `r.offset` calls valid (at that point `l == r`).
452 // - `offsets_l` contains valid offsets into `v` collected during the partitioning of
453 // the last block, so the `l.offset` calls are valid.
455 end_l = end_l.offset(-1);
456 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
460 width(v.as_mut_ptr(), r)
461 } else if start_r < end_r {
462 // The right block remains.
463 // Move its remaining out-of-order elements to the far left.
464 debug_assert_eq!(width(l, r), block_r);
465 while start_r < end_r {
466 // SAFETY: See the reasoning in [remaining-elements-safety].
468 end_r = end_r.offset(-1);
469 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
473 width(v.as_mut_ptr(), l)
475 // Nothing else to do, we're done.
476 width(v.as_mut_ptr(), l)
480 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
481 /// equal to `v[pivot]`.
483 /// Returns a tuple of:
485 /// 1. Number of elements smaller than `v[pivot]`.
486 /// 2. True if `v` was already partitioned.
487 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
489 F: FnMut(&T, &T) -> bool,
491 let (mid, was_partitioned) = {
492 // Place the pivot at the beginning of slice.
494 let (pivot, v) = v.split_at_mut(1);
495 let pivot = &mut pivot[0];
497 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
498 // operation panics, the pivot will be automatically written back into the slice.
500 // SAFETY: `pivot` is a reference to the first element of `v`, so `ptr::read` is safe.
501 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
502 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
505 // Find the first pair of out-of-order elements.
509 // SAFETY: The unsafety below involves indexing an array.
510 // For the first one: We already do the bounds checking here with `l < r`.
511 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
512 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
514 // Find the first element greater than or equal to the pivot.
515 while l < r && is_less(v.get_unchecked(l), pivot) {
519 // Find the last element smaller that the pivot.
520 while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
525 (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
527 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
528 // variable) back into the slice where it originally was. This step is critical in ensuring
532 // Place the pivot between the two partitions.
535 (mid, was_partitioned)
538 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
540 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
541 /// elements smaller than the pivot.
542 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
544 F: FnMut(&T, &T) -> bool,
546 // Place the pivot at the beginning of slice.
548 let (pivot, v) = v.split_at_mut(1);
549 let pivot = &mut pivot[0];
551 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
552 // operation panics, the pivot will be automatically written back into the slice.
553 // SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
554 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
555 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
558 // Now partition the slice.
562 // SAFETY: The unsafety below involves indexing an array.
563 // For the first one: We already do the bounds checking here with `l < r`.
564 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
565 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
567 // Find the first element greater than the pivot.
568 while l < r && !is_less(pivot, v.get_unchecked(l)) {
572 // Find the last element equal to the pivot.
573 while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
582 // Swap the found pair of out-of-order elements.
584 let ptr = v.as_mut_ptr();
585 ptr::swap(ptr.add(l), ptr.add(r));
590 // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
593 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
594 // back into the slice where it originally was. This step is critical in ensuring safety!
597 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
598 /// partitions in quicksort.
600 fn break_patterns<T>(v: &mut [T]) {
603 // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
604 let mut random = len as u32;
605 let mut gen_u32 = || {
606 random ^= random << 13;
607 random ^= random >> 17;
608 random ^= random << 5;
611 let mut gen_usize = || {
612 if usize::BITS <= 32 {
615 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
619 // Take random numbers modulo this number.
620 // The number fits into `usize` because `len` is not greater than `isize::MAX`.
621 let modulus = len.next_power_of_two();
623 // Some pivot candidates will be in the nearby of this index. Let's randomize them.
624 let pos = len / 4 * 2;
627 // Generate a random number modulo `len`. However, in order to avoid costly operations
628 // we first take it modulo a power of two, and then decrease by `len` until it fits
629 // into the range `[0, len - 1]`.
630 let mut other = gen_usize() & (modulus - 1);
632 // `other` is guaranteed to be less than `2 * len`.
637 v.swap(pos - 1 + i, other);
642 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
644 /// Elements in `v` might be reordered in the process.
645 fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
647 F: FnMut(&T, &T) -> bool,
649 // Minimum length to choose the median-of-medians method.
650 // Shorter slices use the simple median-of-three method.
651 const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
652 // Maximum number of swaps that can be performed in this function.
653 const MAX_SWAPS: usize = 4 * 3;
657 // Three indices near which we are going to choose a pivot.
658 let mut a = len / 4 * 1;
659 let mut b = len / 4 * 2;
660 let mut c = len / 4 * 3;
662 // Counts the total number of swaps we are about to perform while sorting indices.
666 // Swaps indices so that `v[a] <= v[b]`.
667 // SAFETY: `len >= 8` so there are at least two elements in the neighborhoods of
668 // `a`, `b` and `c`. This means the three calls to `sort_adjacent` result in
669 // corresponding calls to `sort3` with valid 3-item neighborhoods around each
670 // pointer, which in turn means the calls to `sort2` are done with valid
671 // references. Thus the `v.get_unchecked` calls are safe, as is the `ptr::swap`
673 let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
674 if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
680 // Swaps indices so that `v[a] <= v[b] <= v[c]`.
681 let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
687 if len >= SHORTEST_MEDIAN_OF_MEDIANS {
688 // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
689 let mut sort_adjacent = |a: &mut usize| {
691 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
694 // Find medians in the neighborhoods of `a`, `b`, and `c`.
695 sort_adjacent(&mut a);
696 sort_adjacent(&mut b);
697 sort_adjacent(&mut c);
700 // Find the median among `a`, `b`, and `c`.
701 sort3(&mut a, &mut b, &mut c);
704 if swaps < MAX_SWAPS {
707 // The maximum number of swaps was performed. Chances are the slice is descending or mostly
708 // descending, so reversing will probably help sort it faster.
714 /// Sorts `v` recursively.
716 /// If the slice had a predecessor in the original array, it is specified as `pred`.
718 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
719 /// this function will immediately switch to heapsort.
720 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
722 F: FnMut(&T, &T) -> bool,
724 // Slices of up to this length get sorted using insertion sort.
725 const MAX_INSERTION: usize = 20;
727 // True if the last partitioning was reasonably balanced.
728 let mut was_balanced = true;
729 // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
730 let mut was_partitioned = true;
735 // Very short slices get sorted using insertion sort.
736 if len <= MAX_INSERTION {
737 insertion_sort(v, is_less);
741 // If too many bad pivot choices were made, simply fall back to heapsort in order to
742 // guarantee `O(n * log(n))` worst-case.
744 heapsort(v, is_less);
748 // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
749 // some elements around. Hopefully we'll choose a better pivot this time.
755 // Choose a pivot and try guessing whether the slice is already sorted.
756 let (pivot, likely_sorted) = choose_pivot(v, is_less);
758 // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
759 // selection predicts the slice is likely already sorted...
760 if was_balanced && was_partitioned && likely_sorted {
761 // Try identifying several out-of-order elements and shifting them to correct
762 // positions. If the slice ends up being completely sorted, we're done.
763 if partial_insertion_sort(v, is_less) {
768 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
769 // slice. Partition the slice into elements equal to and elements greater than the pivot.
770 // This case is usually hit when the slice contains many duplicate elements.
771 if let Some(p) = pred {
772 if !is_less(p, &v[pivot]) {
773 let mid = partition_equal(v, pivot, is_less);
775 // Continue sorting elements greater than the pivot.
776 v = &mut { v }[mid..];
781 // Partition the slice.
782 let (mid, was_p) = partition(v, pivot, is_less);
783 was_balanced = cmp::min(mid, len - mid) >= len / 8;
784 was_partitioned = was_p;
786 // Split the slice into `left`, `pivot`, and `right`.
787 let (left, right) = { v }.split_at_mut(mid);
788 let (pivot, right) = right.split_at_mut(1);
789 let pivot = &pivot[0];
791 // Recurse into the shorter side only in order to minimize the total number of recursive
792 // calls and consume less stack space. Then just continue with the longer side (this is
793 // akin to tail recursion).
794 if left.len() < right.len() {
795 recurse(left, is_less, pred, limit);
799 recurse(right, is_less, Some(pivot), limit);
805 /// Sorts `v` using pattern-defeating quicksort, which is *O*(*n* \* log(*n*)) worst-case.
806 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
808 F: FnMut(&T, &T) -> bool,
810 // Sorting has no meaningful behavior on zero-sized types.
811 if mem::size_of::<T>() == 0 {
815 // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
816 let limit = usize::BITS - v.len().leading_zeros();
818 recurse(v, &mut is_less, None, limit);
821 fn partition_at_index_loop<'a, T, F>(
825 mut pred: Option<&'a T>,
827 F: FnMut(&T, &T) -> bool,
830 // For slices of up to this length it's probably faster to simply sort them.
831 const MAX_INSERTION: usize = 10;
832 if v.len() <= MAX_INSERTION {
833 insertion_sort(v, is_less);
838 let (pivot, _) = choose_pivot(v, is_less);
840 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
841 // slice. Partition the slice into elements equal to and elements greater than the pivot.
842 // This case is usually hit when the slice contains many duplicate elements.
843 if let Some(p) = pred {
844 if !is_less(p, &v[pivot]) {
845 let mid = partition_equal(v, pivot, is_less);
847 // If we've passed our index, then we're good.
852 // Otherwise, continue sorting elements greater than the pivot.
860 let (mid, _) = partition(v, pivot, is_less);
862 // Split the slice into `left`, `pivot`, and `right`.
863 let (left, right) = { v }.split_at_mut(mid);
864 let (pivot, right) = right.split_at_mut(1);
865 let pivot = &pivot[0];
869 index = index - mid - 1;
871 } else if mid > index {
874 // If mid == index, then we're done, since partition() guaranteed that all elements
875 // after mid are greater than or equal to mid.
881 pub fn partition_at_index<T, F>(
885 ) -> (&mut [T], &mut T, &mut [T])
887 F: FnMut(&T, &T) -> bool,
889 use cmp::Ordering::Greater;
890 use cmp::Ordering::Less;
892 if index >= v.len() {
893 panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
896 if mem::size_of::<T>() == 0 {
897 // Sorting has no meaningful behavior on zero-sized types. Do nothing.
898 } else if index == v.len() - 1 {
899 // Find max element and place it in the last position of the array. We're free to use
900 // `unwrap()` here because we know v must not be empty.
901 let (max_index, _) = v
904 .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
906 v.swap(max_index, index);
907 } else if index == 0 {
908 // Find min element and place it in the first position of the array. We're free to use
909 // `unwrap()` here because we know v must not be empty.
910 let (min_index, _) = v
913 .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
915 v.swap(min_index, index);
917 partition_at_index_loop(v, index, &mut is_less, None);
920 let (left, right) = v.split_at_mut(index);
921 let (pivot, right) = right.split_at_mut(1);
922 let pivot = &mut pivot[0];