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.
9 // ignore-tidy-undocumented-unsafe
12 use crate::mem::{self, MaybeUninit};
15 /// When dropped, copies from `src` into `dest`.
16 struct CopyOnDrop<T> {
21 impl<T> Drop for CopyOnDrop<T> {
23 // SAFETY: This is a helper class.
24 // Please refer to its usage for correctness.
25 // Namely, one must be sure that `src` and `dst` does not overlap as required by `ptr::copy_nonoverlapping`.
27 ptr::copy_nonoverlapping(self.src, self.dest, 1);
32 /// Shifts the first element to the right until it encounters a greater or equal element.
33 fn shift_head<T, F>(v: &mut [T], is_less: &mut F)
35 F: FnMut(&T, &T) -> bool,
38 // SAFETY: The unsafe operations below involves indexing without a bound check (`get_unchecked` and `get_unchecked_mut`)
39 // and copying memory (`ptr::copy_nonoverlapping`).
42 // 1. We checked the size of the array to >=2.
43 // 2. All the indexing that we will do is always between {0 <= index < len} at most.
46 // 1. We are obtaining pointers to references which are guaranteed to be valid.
47 // 2. They cannot overlap because we obtain pointers to difference indices of the slice.
48 // Namely, `i` and `i-1`.
49 // 3. If the slice is properly aligned, the elements are properly aligned.
50 // It is the caller's responsibility to make sure the slice is properly aligned.
52 // See comments below for further detail.
54 // If the first two elements are out-of-order...
55 if len >= 2 && is_less(v.get_unchecked(1), v.get_unchecked(0)) {
56 // Read the first element into a stack-allocated variable. If a following comparison
57 // operation panics, `hole` will get dropped and automatically write the element back
59 let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(0)));
60 let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.get_unchecked_mut(1) };
61 ptr::copy_nonoverlapping(v.get_unchecked(1), v.get_unchecked_mut(0), 1);
64 if !is_less(v.get_unchecked(i), &*tmp) {
68 // Move `i`-th element one place to the left, thus shifting the hole to the right.
69 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i - 1), 1);
70 hole.dest = v.get_unchecked_mut(i);
72 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
77 /// Shifts the last element to the left until it encounters a smaller or equal element.
78 fn shift_tail<T, F>(v: &mut [T], is_less: &mut F)
80 F: FnMut(&T, &T) -> bool,
83 // SAFETY: The unsafe operations below involves indexing without a bound check (`get_unchecked` and `get_unchecked_mut`)
84 // and copying memory (`ptr::copy_nonoverlapping`).
87 // 1. We checked the size of the array to >= 2.
88 // 2. All the indexing that we will do is always between `0 <= index < len-1` at most.
91 // 1. We are obtaining pointers to references which are guaranteed to be valid.
92 // 2. They cannot overlap because we obtain pointers to difference indices of the slice.
93 // Namely, `i` and `i+1`.
94 // 3. If the slice is properly aligned, the elements are properly aligned.
95 // It is the caller's responsibility to make sure the slice is properly aligned.
97 // See comments below for further detail.
99 // If the last two elements are out-of-order...
100 if len >= 2 && is_less(v.get_unchecked(len - 1), v.get_unchecked(len - 2)) {
101 // Read the last element into a stack-allocated variable. If a following comparison
102 // operation panics, `hole` will get dropped and automatically write the element back
104 let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(len - 1)));
105 let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.get_unchecked_mut(len - 2) };
106 ptr::copy_nonoverlapping(v.get_unchecked(len - 2), v.get_unchecked_mut(len - 1), 1);
108 for i in (0..len - 2).rev() {
109 if !is_less(&*tmp, v.get_unchecked(i)) {
113 // Move `i`-th element one place to the right, thus shifting the hole to the left.
114 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i + 1), 1);
115 hole.dest = v.get_unchecked_mut(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 pub fn heapsort<T, F>(v: &mut [T], is_less: &mut F)
185 F: FnMut(&T, &T) -> bool,
187 // This binary heap respects the invariant `parent >= child`.
188 let mut sift_down = |v: &mut [T], mut node| {
190 // Children of `node`:
191 let left = 2 * node + 1;
192 let right = 2 * node + 2;
194 // Choose the greater child.
196 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
198 // Stop if the invariant holds at `node`.
199 if greater >= v.len() || !is_less(&v[node], &v[greater]) {
203 // Swap `node` with the greater child, move one step down, and continue sifting.
204 v.swap(node, greater);
209 // Build the heap in linear time.
210 for i in (0..v.len() / 2).rev() {
214 // Pop maximal elements from the heap.
215 for i in (1..v.len()).rev() {
217 sift_down(&mut v[..i], 0);
221 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
224 /// Returns the number of elements smaller than `pivot`.
226 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
227 /// This idea is presented in the [BlockQuicksort][pdf] paper.
229 /// [pdf]: http://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
230 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
232 F: FnMut(&T, &T) -> bool,
234 // Number of elements in a typical block.
235 const BLOCK: usize = 128;
237 // The partitioning algorithm repeats the following steps until completion:
239 // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
240 // 2. Trace a block from the right side to identify elements smaller than the pivot.
241 // 3. Exchange the identified elements between the left and right side.
243 // We keep the following variables for a block of elements:
245 // 1. `block` - Number of elements in the block.
246 // 2. `start` - Start pointer into the `offsets` array.
247 // 3. `end` - End pointer into the `offsets` array.
248 // 4. `offsets - Indices of out-of-order elements within the block.
250 // The current block on the left side (from `l` to `l.add(block_l)`).
251 let mut l = v.as_mut_ptr();
252 let mut block_l = BLOCK;
253 let mut start_l = ptr::null_mut();
254 let mut end_l = ptr::null_mut();
255 let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
257 // The current block on the right side (from `r.sub(block_r)` to `r`).
258 // SAFETY: The documentation for .add() specifically mention that `vec.as_ptr().add(vec.len())` is always safe`
259 let mut r = unsafe { l.add(v.len()) };
260 let mut block_r = BLOCK;
261 let mut start_r = ptr::null_mut();
262 let mut end_r = ptr::null_mut();
263 let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
265 // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
266 // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
268 // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
269 fn width<T>(l: *mut T, r: *mut T) -> usize {
270 assert!(mem::size_of::<T>() > 0);
271 (r as usize - l as usize) / mem::size_of::<T>()
275 // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
276 // some patch-up work in order to partition the remaining elements in between.
277 let is_done = width(l, r) <= 2 * BLOCK;
280 // Number of remaining elements (still not compared to the pivot).
281 let mut rem = width(l, r);
282 if start_l < end_l || start_r < end_r {
286 // Adjust block sizes so that the left and right block don't overlap, but get perfectly
287 // aligned to cover the whole remaining gap.
290 } else if start_r < end_r {
294 block_r = rem - block_l;
296 debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
297 debug_assert!(width(l, r) == block_l + block_r);
300 if start_l == end_l {
301 // Trace `block_l` elements from the left side.
302 start_l = MaybeUninit::first_ptr_mut(&mut offsets_l);
303 end_l = MaybeUninit::first_ptr_mut(&mut offsets_l);
306 for i in 0..block_l {
307 // SAFETY: The unsafety operations below involve the usage of the `offset`.
308 // According to the conditions required by the function, we satisfy them because:
309 // 1. `offsets_l` is stack-allocated, and thus considered separate allocated object.
310 // 2. The function `is_less` returns a `bool`.
311 // Casting a `bool` will never overflow `isize`.
312 // 3. We have guaranteed that `block_l` will be `<= BLOCK`.
313 // Plus, `end_l` was initially set to the begin pointer of `offsets_` which was declared on the stack.
314 // 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.
315 // Another unsafety operation here is dereferencing `elem`.
316 // However, `elem` was initially the begin pointer to the slice which is always valid.
318 // Branchless comparison.
320 end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
321 elem = elem.offset(1);
326 if start_r == end_r {
327 // Trace `block_r` elements from the right side.
328 start_r = MaybeUninit::first_ptr_mut(&mut offsets_r);
329 end_r = MaybeUninit::first_ptr_mut(&mut offsets_r);
332 for i in 0..block_r {
333 // SAFETY: The unsafety operations below involve the usage of the `offset`.
334 // According to the conditions required by the function, we satisfy them because:
335 // 1. `offsets_r` is stack-allocated, and thus considered separate allocated object.
336 // 2. The function `is_less` returns a `bool`.
337 // Casting a `bool` will never overflow `isize`.
338 // 3. We have guaranteed that `block_r` will be `<= BLOCK`.
339 // Plus, `end_r` was initially set to the begin pointer of `offsets_` which was declared on the stack.
340 // 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.
341 // Another unsafety operation here is dereferencing `elem`.
342 // However, `elem` was initially `1 * sizeof(T)` past the end and we decrement it by `1 * sizeof(T)` before accessing it.
343 // Plus, `block_r` was asserted to be less than `BLOCK` and `elem` will therefore at most be pointing to the beginning of the slice.
345 // Branchless comparison.
346 elem = elem.offset(-1);
348 end_r = end_r.offset(is_less(&*elem, pivot) as isize);
353 // Number of out-of-order elements to swap between the left and right side.
354 let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
359 l.offset(*start_l as isize)
364 r.offset(-(*start_r as isize) - 1)
368 // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
369 // permutation. This is not strictly equivalent to swapping, but produces a similar
370 // result using fewer memory operations.
372 let tmp = ptr::read(left!());
373 ptr::copy_nonoverlapping(right!(), left!(), 1);
376 start_l = start_l.offset(1);
377 ptr::copy_nonoverlapping(left!(), right!(), 1);
378 start_r = start_r.offset(1);
379 ptr::copy_nonoverlapping(right!(), left!(), 1);
382 ptr::copy_nonoverlapping(&tmp, right!(), 1);
384 start_l = start_l.offset(1);
385 start_r = start_r.offset(1);
389 if start_l == end_l {
390 // All out-of-order elements in the left block were moved. Move to the next block.
391 l = unsafe { l.offset(block_l as isize) };
394 if start_r == end_r {
395 // All out-of-order elements in the right block were moved. Move to the previous block.
396 r = unsafe { r.offset(-(block_r as isize)) };
404 // All that remains now is at most one block (either the left or the right) with out-of-order
405 // elements that need to be moved. Such remaining elements can be simply shifted to the end
406 // within their block.
409 // The left block remains.
410 // Move its remaining out-of-order elements to the far right.
411 debug_assert_eq!(width(l, r), block_l);
412 while start_l < end_l {
414 end_l = end_l.offset(-1);
415 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
419 width(v.as_mut_ptr(), r)
420 } else if start_r < end_r {
421 // The right block remains.
422 // Move its remaining out-of-order elements to the far left.
423 debug_assert_eq!(width(l, r), block_r);
424 while start_r < end_r {
426 end_r = end_r.offset(-1);
427 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
431 width(v.as_mut_ptr(), l)
433 // Nothing else to do, we're done.
434 width(v.as_mut_ptr(), l)
438 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
439 /// equal to `v[pivot]`.
441 /// Returns a tuple of:
443 /// 1. Number of elements smaller than `v[pivot]`.
444 /// 2. True if `v` was already partitioned.
445 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
447 F: FnMut(&T, &T) -> bool,
449 let (mid, was_partitioned) = {
450 // Place the pivot at the beginning of slice.
452 let (pivot, v) = v.split_at_mut(1);
453 let pivot = &mut pivot[0];
455 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
456 // operation panics, the pivot will be automatically written back into the slice.
457 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
458 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
461 // Find the first pair of out-of-order elements.
465 // SAFETY: The unsafety below involves indexing an array.
466 // For the first one: We already do the bounds checking here with `l < r`.
467 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
468 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
470 // Find the first element greater than or equal to the pivot.
471 while l < r && is_less(v.get_unchecked(l), pivot) {
475 // Find the last element smaller that the pivot.
476 while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
481 (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
483 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
484 // variable) back into the slice where it originally was. This step is critical in ensuring
488 // Place the pivot between the two partitions.
491 (mid, was_partitioned)
494 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
496 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
497 /// elements smaller than the pivot.
498 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
500 F: FnMut(&T, &T) -> bool,
502 // Place the pivot at the beginning of slice.
504 let (pivot, v) = v.split_at_mut(1);
505 let pivot = &mut pivot[0];
507 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
508 // operation panics, the pivot will be automatically written back into the slice.
509 // SAFETY: The pointer here is valid because it is obtained from a reference to a slice.
510 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
511 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
514 // Now partition the slice.
518 // SAFETY: The unsafety below involves indexing an array.
519 // For the first one: We already do the bounds checking here with `l < r`.
520 // For the second one: We initially have `l == 0` and `r == v.len()` and we checked that `l < r` at every indexing operation.
521 // From here we know that `r` must be at least `r == l` which was shown to be valid from the first one.
523 // Find the first element greater than the pivot.
524 while l < r && !is_less(pivot, v.get_unchecked(l)) {
528 // Find the last element equal to the pivot.
529 while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
538 // Swap the found pair of out-of-order elements.
540 ptr::swap(v.get_unchecked_mut(l), v.get_unchecked_mut(r));
545 // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
548 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
549 // back into the slice where it originally was. This step is critical in ensuring safety!
552 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
553 /// partitions in quicksort.
555 fn break_patterns<T>(v: &mut [T]) {
558 // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
559 let mut random = len as u32;
560 let mut gen_u32 = || {
561 random ^= random << 13;
562 random ^= random >> 17;
563 random ^= random << 5;
566 let mut gen_usize = || {
567 if mem::size_of::<usize>() <= 4 {
570 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
574 // Take random numbers modulo this number.
575 // The number fits into `usize` because `len` is not greater than `isize::MAX`.
576 let modulus = len.next_power_of_two();
578 // Some pivot candidates will be in the nearby of this index. Let's randomize them.
579 let pos = len / 4 * 2;
582 // Generate a random number modulo `len`. However, in order to avoid costly operations
583 // we first take it modulo a power of two, and then decrease by `len` until it fits
584 // into the range `[0, len - 1]`.
585 let mut other = gen_usize() & (modulus - 1);
587 // `other` is guaranteed to be less than `2 * len`.
592 v.swap(pos - 1 + i, other);
597 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
599 /// Elements in `v` might be reordered in the process.
600 fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
602 F: FnMut(&T, &T) -> bool,
604 // Minimum length to choose the median-of-medians method.
605 // Shorter slices use the simple median-of-three method.
606 const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
607 // Maximum number of swaps that can be performed in this function.
608 const MAX_SWAPS: usize = 4 * 3;
612 // Three indices near which we are going to choose a pivot.
613 let mut a = len / 4 * 1;
614 let mut b = len / 4 * 2;
615 let mut c = len / 4 * 3;
617 // Counts the total number of swaps we are about to perform while sorting indices.
621 // Swaps indices so that `v[a] <= v[b]`.
622 let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
623 if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
629 // Swaps indices so that `v[a] <= v[b] <= v[c]`.
630 let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
636 if len >= SHORTEST_MEDIAN_OF_MEDIANS {
637 // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
638 let mut sort_adjacent = |a: &mut usize| {
640 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
643 // Find medians in the neighborhoods of `a`, `b`, and `c`.
644 sort_adjacent(&mut a);
645 sort_adjacent(&mut b);
646 sort_adjacent(&mut c);
649 // Find the median among `a`, `b`, and `c`.
650 sort3(&mut a, &mut b, &mut c);
653 if swaps < MAX_SWAPS {
656 // The maximum number of swaps was performed. Chances are the slice is descending or mostly
657 // descending, so reversing will probably help sort it faster.
663 /// Sorts `v` recursively.
665 /// If the slice had a predecessor in the original array, it is specified as `pred`.
667 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
668 /// this function will immediately switch to heapsort.
669 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: usize)
671 F: FnMut(&T, &T) -> bool,
673 // Slices of up to this length get sorted using insertion sort.
674 const MAX_INSERTION: usize = 20;
676 // True if the last partitioning was reasonably balanced.
677 let mut was_balanced = true;
678 // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
679 let mut was_partitioned = true;
684 // Very short slices get sorted using insertion sort.
685 if len <= MAX_INSERTION {
686 insertion_sort(v, is_less);
690 // If too many bad pivot choices were made, simply fall back to heapsort in order to
691 // guarantee `O(n * log(n))` worst-case.
693 heapsort(v, is_less);
697 // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
698 // some elements around. Hopefully we'll choose a better pivot this time.
704 // Choose a pivot and try guessing whether the slice is already sorted.
705 let (pivot, likely_sorted) = choose_pivot(v, is_less);
707 // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
708 // selection predicts the slice is likely already sorted...
709 if was_balanced && was_partitioned && likely_sorted {
710 // Try identifying several out-of-order elements and shifting them to correct
711 // positions. If the slice ends up being completely sorted, we're done.
712 if partial_insertion_sort(v, is_less) {
717 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
718 // slice. Partition the slice into elements equal to and elements greater than the pivot.
719 // This case is usually hit when the slice contains many duplicate elements.
720 if let Some(p) = pred {
721 if !is_less(p, &v[pivot]) {
722 let mid = partition_equal(v, pivot, is_less);
724 // Continue sorting elements greater than the pivot.
725 v = &mut { v }[mid..];
730 // Partition the slice.
731 let (mid, was_p) = partition(v, pivot, is_less);
732 was_balanced = cmp::min(mid, len - mid) >= len / 8;
733 was_partitioned = was_p;
735 // Split the slice into `left`, `pivot`, and `right`.
736 let (left, right) = { v }.split_at_mut(mid);
737 let (pivot, right) = right.split_at_mut(1);
738 let pivot = &pivot[0];
740 // Recurse into the shorter side only in order to minimize the total number of recursive
741 // calls and consume less stack space. Then just continue with the longer side (this is
742 // akin to tail recursion).
743 if left.len() < right.len() {
744 recurse(left, is_less, pred, limit);
748 recurse(right, is_less, Some(pivot), limit);
754 /// Sorts `v` using pattern-defeating quicksort, which is *O*(*n* \* log(*n*)) worst-case.
755 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
757 F: FnMut(&T, &T) -> bool,
759 // Sorting has no meaningful behavior on zero-sized types.
760 if mem::size_of::<T>() == 0 {
764 // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
765 let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
767 recurse(v, &mut is_less, None, limit);
770 fn partition_at_index_loop<'a, T, F>(
774 mut pred: Option<&'a T>,
776 F: FnMut(&T, &T) -> bool,
779 // For slices of up to this length it's probably faster to simply sort them.
780 const MAX_INSERTION: usize = 10;
781 if v.len() <= MAX_INSERTION {
782 insertion_sort(v, is_less);
787 let (pivot, _) = choose_pivot(v, is_less);
789 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
790 // slice. Partition the slice into elements equal to and elements greater than the pivot.
791 // This case is usually hit when the slice contains many duplicate elements.
792 if let Some(p) = pred {
793 if !is_less(p, &v[pivot]) {
794 let mid = partition_equal(v, pivot, is_less);
796 // If we've passed our index, then we're good.
801 // Otherwise, continue sorting elements greater than the pivot.
809 let (mid, _) = partition(v, pivot, is_less);
811 // Split the slice into `left`, `pivot`, and `right`.
812 let (left, right) = { v }.split_at_mut(mid);
813 let (pivot, right) = right.split_at_mut(1);
814 let pivot = &pivot[0];
818 index = index - mid - 1;
820 } else if mid > index {
823 // If mid == index, then we're done, since partition() guaranteed that all elements
824 // after mid are greater than or equal to mid.
830 pub fn partition_at_index<T, F>(
834 ) -> (&mut [T], &mut T, &mut [T])
836 F: FnMut(&T, &T) -> bool,
838 use cmp::Ordering::Greater;
839 use cmp::Ordering::Less;
841 if index >= v.len() {
842 panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
845 if mem::size_of::<T>() == 0 {
846 // Sorting has no meaningful behavior on zero-sized types. Do nothing.
847 } else if index == v.len() - 1 {
848 // Find max element and place it in the last position of the array. We're free to use
849 // `unwrap()` here because we know v must not be empty.
850 let (max_index, _) = v
853 .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
855 v.swap(max_index, index);
856 } else if index == 0 {
857 // Find min element and place it in the first position of the array. We're free to use
858 // `unwrap()` here because we know v must not be empty.
859 let (min_index, _) = v
862 .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
864 v.swap(min_index, index);
866 partition_at_index_loop(v, index, &mut is_less, None);
869 let (left, right) = v.split_at_mut(index);
870 let (pivot, right) = right.split_at_mut(1);
871 let pivot = &mut pivot[0];