3 //! This module contains an sort 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> {
24 ptr::copy_nonoverlapping(self.src, self.dest, 1);
29 /// Shifts the first element to the right until it encounters a greater or equal element.
30 fn shift_head<T, F>(v: &mut [T], is_less: &mut F)
32 F: FnMut(&T, &T) -> bool,
36 // If the first two elements are out-of-order...
37 if len >= 2 && is_less(v.get_unchecked(1), v.get_unchecked(0)) {
38 // Read the first element into a stack-allocated variable. If a following comparison
39 // operation panics, `hole` will get dropped and automatically write the element back
41 let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(0)));
42 let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.get_unchecked_mut(1) };
43 ptr::copy_nonoverlapping(v.get_unchecked(1), v.get_unchecked_mut(0), 1);
46 if !is_less(v.get_unchecked(i), &*tmp) {
50 // Move `i`-th element one place to the left, thus shifting the hole to the right.
51 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i - 1), 1);
52 hole.dest = v.get_unchecked_mut(i);
54 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
59 /// Shifts the last element to the left until it encounters a smaller or equal element.
60 fn shift_tail<T, F>(v: &mut [T], is_less: &mut F)
62 F: FnMut(&T, &T) -> bool,
66 // If the last two elements are out-of-order...
67 if len >= 2 && is_less(v.get_unchecked(len - 1), v.get_unchecked(len - 2)) {
68 // Read the last element into a stack-allocated variable. If a following comparison
69 // operation panics, `hole` will get dropped and automatically write the element back
71 let mut tmp = mem::ManuallyDrop::new(ptr::read(v.get_unchecked(len - 1)));
72 let mut hole = CopyOnDrop { src: &mut *tmp, dest: v.get_unchecked_mut(len - 2) };
73 ptr::copy_nonoverlapping(v.get_unchecked(len - 2), v.get_unchecked_mut(len - 1), 1);
75 for i in (0..len - 2).rev() {
76 if !is_less(&*tmp, v.get_unchecked(i)) {
80 // Move `i`-th element one place to the right, thus shifting the hole to the left.
81 ptr::copy_nonoverlapping(v.get_unchecked(i), v.get_unchecked_mut(i + 1), 1);
82 hole.dest = v.get_unchecked_mut(i);
84 // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
89 /// Partially sorts a slice by shifting several out-of-order elements around.
91 /// Returns `true` if the slice is sorted at the end. This function is `O(n)` worst-case.
93 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
95 F: FnMut(&T, &T) -> bool,
97 // Maximum number of adjacent out-of-order pairs that will get shifted.
98 const MAX_STEPS: usize = 5;
99 // If the slice is shorter than this, don't shift any elements.
100 const SHORTEST_SHIFTING: usize = 50;
105 for _ in 0..MAX_STEPS {
107 // Find the next pair of adjacent out-of-order elements.
108 while i < len && !is_less(v.get_unchecked(i), v.get_unchecked(i - 1)) {
118 // Don't shift elements on short arrays, that has a performance cost.
119 if len < SHORTEST_SHIFTING {
123 // Swap the found pair of elements. This puts them in correct order.
126 // Shift the smaller element to the left.
127 shift_tail(&mut v[..i], is_less);
128 // Shift the greater element to the right.
129 shift_head(&mut v[i..], is_less);
132 // Didn't manage to sort the slice in the limited number of steps.
136 /// Sorts a slice using insertion sort, which is `O(n^2)` worst-case.
137 fn insertion_sort<T, F>(v: &mut [T], is_less: &mut F)
139 F: FnMut(&T, &T) -> bool,
141 for i in 1..v.len() {
142 shift_tail(&mut v[..i + 1], is_less);
146 /// Sorts `v` using heapsort, which guarantees `O(n log n)` worst-case.
148 pub fn heapsort<T, F>(v: &mut [T], is_less: &mut F)
150 F: FnMut(&T, &T) -> bool,
152 // This binary heap respects the invariant `parent >= child`.
153 let mut sift_down = |v: &mut [T], mut node| {
155 // Children of `node`:
156 let left = 2 * node + 1;
157 let right = 2 * node + 2;
159 // Choose the greater child.
161 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
163 // Stop if the invariant holds at `node`.
164 if greater >= v.len() || !is_less(&v[node], &v[greater]) {
168 // Swap `node` with the greater child, move one step down, and continue sifting.
169 v.swap(node, greater);
174 // Build the heap in linear time.
175 for i in (0..v.len() / 2).rev() {
179 // Pop maximal elements from the heap.
180 for i in (1..v.len()).rev() {
182 sift_down(&mut v[..i], 0);
186 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
189 /// Returns the number of elements smaller than `pivot`.
191 /// Partitioning is performed block-by-block in order to minimize the cost of branching operations.
192 /// This idea is presented in the [BlockQuicksort][pdf] paper.
194 /// [pdf]: http://drops.dagstuhl.de/opus/volltexte/2016/6389/pdf/LIPIcs-ESA-2016-38.pdf
195 fn partition_in_blocks<T, F>(v: &mut [T], pivot: &T, is_less: &mut F) -> usize
197 F: FnMut(&T, &T) -> bool,
199 // Number of elements in a typical block.
200 const BLOCK: usize = 128;
202 // The partitioning algorithm repeats the following steps until completion:
204 // 1. Trace a block from the left side to identify elements greater than or equal to the pivot.
205 // 2. Trace a block from the right side to identify elements smaller than the pivot.
206 // 3. Exchange the identified elements between the left and right side.
208 // We keep the following variables for a block of elements:
210 // 1. `block` - Number of elements in the block.
211 // 2. `start` - Start pointer into the `offsets` array.
212 // 3. `end` - End pointer into the `offsets` array.
213 // 4. `offsets - Indices of out-of-order elements within the block.
215 // The current block on the left side (from `l` to `l.add(block_l)`).
216 let mut l = v.as_mut_ptr();
217 let mut block_l = BLOCK;
218 let mut start_l = ptr::null_mut();
219 let mut end_l = ptr::null_mut();
220 let mut offsets_l = [MaybeUninit::<u8>::uninit(); BLOCK];
222 // The current block on the right side (from `r.sub(block_r)` to `r`).
223 let mut r = unsafe { l.add(v.len()) };
224 let mut block_r = BLOCK;
225 let mut start_r = ptr::null_mut();
226 let mut end_r = ptr::null_mut();
227 let mut offsets_r = [MaybeUninit::<u8>::uninit(); BLOCK];
229 // FIXME: When we get VLAs, try creating one array of length `min(v.len(), 2 * BLOCK)` rather
230 // than two fixed-size arrays of length `BLOCK`. VLAs might be more cache-efficient.
232 // Returns the number of elements between pointers `l` (inclusive) and `r` (exclusive).
233 fn width<T>(l: *mut T, r: *mut T) -> usize {
234 assert!(mem::size_of::<T>() > 0);
235 (r as usize - l as usize) / mem::size_of::<T>()
239 // We are done with partitioning block-by-block when `l` and `r` get very close. Then we do
240 // some patch-up work in order to partition the remaining elements in between.
241 let is_done = width(l, r) <= 2 * BLOCK;
244 // Number of remaining elements (still not compared to the pivot).
245 let mut rem = width(l, r);
246 if start_l < end_l || start_r < end_r {
250 // Adjust block sizes so that the left and right block don't overlap, but get perfectly
251 // aligned to cover the whole remaining gap.
254 } else if start_r < end_r {
258 block_r = rem - block_l;
260 debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
261 debug_assert!(width(l, r) == block_l + block_r);
264 if start_l == end_l {
265 // Trace `block_l` elements from the left side.
266 start_l = MaybeUninit::first_ptr_mut(&mut offsets_l);
267 end_l = MaybeUninit::first_ptr_mut(&mut offsets_l);
270 for i in 0..block_l {
272 // Branchless comparison.
274 end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
275 elem = elem.offset(1);
280 if start_r == end_r {
281 // Trace `block_r` elements from the right side.
282 start_r = MaybeUninit::first_ptr_mut(&mut offsets_r);
283 end_r = MaybeUninit::first_ptr_mut(&mut offsets_r);
286 for i in 0..block_r {
288 // Branchless comparison.
289 elem = elem.offset(-1);
291 end_r = end_r.offset(is_less(&*elem, pivot) as isize);
296 // Number of out-of-order elements to swap between the left and right side.
297 let count = cmp::min(width(start_l, end_l), width(start_r, end_r));
302 l.offset(*start_l as isize)
307 r.offset(-(*start_r as isize) - 1)
311 // Instead of swapping one pair at the time, it is more efficient to perform a cyclic
312 // permutation. This is not strictly equivalent to swapping, but produces a similar
313 // result using fewer memory operations.
315 let tmp = ptr::read(left!());
316 ptr::copy_nonoverlapping(right!(), left!(), 1);
319 start_l = start_l.offset(1);
320 ptr::copy_nonoverlapping(left!(), right!(), 1);
321 start_r = start_r.offset(1);
322 ptr::copy_nonoverlapping(right!(), left!(), 1);
325 ptr::copy_nonoverlapping(&tmp, right!(), 1);
327 start_l = start_l.offset(1);
328 start_r = start_r.offset(1);
332 if start_l == end_l {
333 // All out-of-order elements in the left block were moved. Move to the next block.
334 l = unsafe { l.offset(block_l as isize) };
337 if start_r == end_r {
338 // All out-of-order elements in the right block were moved. Move to the previous block.
339 r = unsafe { r.offset(-(block_r as isize)) };
347 // All that remains now is at most one block (either the left or the right) with out-of-order
348 // elements that need to be moved. Such remaining elements can be simply shifted to the end
349 // within their block.
352 // The left block remains.
353 // Move its remaining out-of-order elements to the far right.
354 debug_assert_eq!(width(l, r), block_l);
355 while start_l < end_l {
357 end_l = end_l.offset(-1);
358 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
362 width(v.as_mut_ptr(), r)
363 } else if start_r < end_r {
364 // The right block remains.
365 // Move its remaining out-of-order elements to the far left.
366 debug_assert_eq!(width(l, r), block_r);
367 while start_r < end_r {
369 end_r = end_r.offset(-1);
370 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
374 width(v.as_mut_ptr(), l)
376 // Nothing else to do, we're done.
377 width(v.as_mut_ptr(), l)
381 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
382 /// equal to `v[pivot]`.
384 /// Returns a tuple of:
386 /// 1. Number of elements smaller than `v[pivot]`.
387 /// 2. True if `v` was already partitioned.
388 fn partition<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> (usize, bool)
390 F: FnMut(&T, &T) -> bool,
392 let (mid, was_partitioned) = {
393 // Place the pivot at the beginning of slice.
395 let (pivot, v) = v.split_at_mut(1);
396 let pivot = &mut pivot[0];
398 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
399 // operation panics, the pivot will be automatically written back into the slice.
400 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
401 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
404 // Find the first pair of out-of-order elements.
408 // Find the first element greater then or equal to the pivot.
409 while l < r && is_less(v.get_unchecked(l), pivot) {
413 // Find the last element smaller that the pivot.
414 while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
419 (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
421 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated
422 // variable) back into the slice where it originally was. This step is critical in ensuring
426 // Place the pivot between the two partitions.
429 (mid, was_partitioned)
432 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
434 /// Returns the number of elements equal to the pivot. It is assumed that `v` does not contain
435 /// elements smaller than the pivot.
436 fn partition_equal<T, F>(v: &mut [T], pivot: usize, is_less: &mut F) -> usize
438 F: FnMut(&T, &T) -> bool,
440 // Place the pivot at the beginning of slice.
442 let (pivot, v) = v.split_at_mut(1);
443 let pivot = &mut pivot[0];
445 // Read the pivot into a stack-allocated variable for efficiency. If a following comparison
446 // operation panics, the pivot will be automatically written back into the slice.
447 let mut tmp = mem::ManuallyDrop::new(unsafe { ptr::read(pivot) });
448 let _pivot_guard = CopyOnDrop { src: &mut *tmp, dest: pivot };
451 // Now partition the slice.
456 // Find the first element greater that the pivot.
457 while l < r && !is_less(pivot, v.get_unchecked(l)) {
461 // Find the last element equal to the pivot.
462 while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
471 // Swap the found pair of out-of-order elements.
473 ptr::swap(v.get_unchecked_mut(l), v.get_unchecked_mut(r));
478 // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
481 // `_pivot_guard` goes out of scope and writes the pivot (which is a stack-allocated variable)
482 // back into the slice where it originally was. This step is critical in ensuring safety!
485 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
486 /// partitions in quicksort.
488 fn break_patterns<T>(v: &mut [T]) {
491 // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia.
492 let mut random = len as u32;
493 let mut gen_u32 = || {
494 random ^= random << 13;
495 random ^= random >> 17;
496 random ^= random << 5;
499 let mut gen_usize = || {
500 if mem::size_of::<usize>() <= 4 {
503 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
507 // Take random numbers modulo this number.
508 // The number fits into `usize` because `len` is not greater than `isize::MAX`.
509 let modulus = len.next_power_of_two();
511 // Some pivot candidates will be in the nearby of this index. Let's randomize them.
512 let pos = len / 4 * 2;
515 // Generate a random number modulo `len`. However, in order to avoid costly operations
516 // we first take it modulo a power of two, and then decrease by `len` until it fits
517 // into the range `[0, len - 1]`.
518 let mut other = gen_usize() & (modulus - 1);
520 // `other` is guaranteed to be less than `2 * len`.
525 v.swap(pos - 1 + i, other);
530 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
532 /// Elements in `v` might be reordered in the process.
533 fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
535 F: FnMut(&T, &T) -> bool,
537 // Minimum length to choose the median-of-medians method.
538 // Shorter slices use the simple median-of-three method.
539 const SHORTEST_MEDIAN_OF_MEDIANS: usize = 50;
540 // Maximum number of swaps that can be performed in this function.
541 const MAX_SWAPS: usize = 4 * 3;
545 // Three indices near which we are going to choose a pivot.
546 let mut a = len / 4 * 1;
547 let mut b = len / 4 * 2;
548 let mut c = len / 4 * 3;
550 // Counts the total number of swaps we are about to perform while sorting indices.
554 // Swaps indices so that `v[a] <= v[b]`.
555 let mut sort2 = |a: &mut usize, b: &mut usize| unsafe {
556 if is_less(v.get_unchecked(*b), v.get_unchecked(*a)) {
562 // Swaps indices so that `v[a] <= v[b] <= v[c]`.
563 let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
569 if len >= SHORTEST_MEDIAN_OF_MEDIANS {
570 // Finds the median of `v[a - 1], v[a], v[a + 1]` and stores the index into `a`.
571 let mut sort_adjacent = |a: &mut usize| {
573 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
576 // Find medians in the neighborhoods of `a`, `b`, and `c`.
577 sort_adjacent(&mut a);
578 sort_adjacent(&mut b);
579 sort_adjacent(&mut c);
582 // Find the median among `a`, `b`, and `c`.
583 sort3(&mut a, &mut b, &mut c);
586 if swaps < MAX_SWAPS {
589 // The maximum number of swaps was performed. Chances are the slice is descending or mostly
590 // descending, so reversing will probably help sort it faster.
596 /// Sorts `v` recursively.
598 /// If the slice had a predecessor in the original array, it is specified as `pred`.
600 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
601 /// this function will immediately switch to heapsort.
602 fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: usize)
604 F: FnMut(&T, &T) -> bool,
606 // Slices of up to this length get sorted using insertion sort.
607 const MAX_INSERTION: usize = 20;
609 // True if the last partitioning was reasonably balanced.
610 let mut was_balanced = true;
611 // True if the last partitioning didn't shuffle elements (the slice was already partitioned).
612 let mut was_partitioned = true;
617 // Very short slices get sorted using insertion sort.
618 if len <= MAX_INSERTION {
619 insertion_sort(v, is_less);
623 // If too many bad pivot choices were made, simply fall back to heapsort in order to
624 // guarantee `O(n log n)` worst-case.
626 heapsort(v, is_less);
630 // If the last partitioning was imbalanced, try breaking patterns in the slice by shuffling
631 // some elements around. Hopefully we'll choose a better pivot this time.
637 // Choose a pivot and try guessing whether the slice is already sorted.
638 let (pivot, likely_sorted) = choose_pivot(v, is_less);
640 // If the last partitioning was decently balanced and didn't shuffle elements, and if pivot
641 // selection predicts the slice is likely already sorted...
642 if was_balanced && was_partitioned && likely_sorted {
643 // Try identifying several out-of-order elements and shifting them to correct
644 // positions. If the slice ends up being completely sorted, we're done.
645 if partial_insertion_sort(v, is_less) {
650 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
651 // slice. Partition the slice into elements equal to and elements greater than the pivot.
652 // This case is usually hit when the slice contains many duplicate elements.
653 if let Some(p) = pred {
654 if !is_less(p, &v[pivot]) {
655 let mid = partition_equal(v, pivot, is_less);
657 // Continue sorting elements greater than the pivot.
658 v = &mut { v }[mid..];
663 // Partition the slice.
664 let (mid, was_p) = partition(v, pivot, is_less);
665 was_balanced = cmp::min(mid, len - mid) >= len / 8;
666 was_partitioned = was_p;
668 // Split the slice into `left`, `pivot`, and `right`.
669 let (left, right) = { v }.split_at_mut(mid);
670 let (pivot, right) = right.split_at_mut(1);
671 let pivot = &pivot[0];
673 // Recurse into the shorter side only in order to minimize the total number of recursive
674 // calls and consume less stack space. Then just continue with the longer side (this is
675 // akin to tail recursion).
676 if left.len() < right.len() {
677 recurse(left, is_less, pred, limit);
681 recurse(right, is_less, Some(pivot), limit);
687 /// Sorts `v` using pattern-defeating quicksort, which is `O(n log n)` worst-case.
688 pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
690 F: FnMut(&T, &T) -> bool,
692 // Sorting has no meaningful behavior on zero-sized types.
693 if mem::size_of::<T>() == 0 {
697 // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
698 let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
700 recurse(v, &mut is_less, None, limit);
703 fn partition_at_index_loop<'a, T, F>(
707 mut pred: Option<&'a T>,
709 F: FnMut(&T, &T) -> bool,
712 // For slices of up to this length it's probably faster to simply sort them.
713 const MAX_INSERTION: usize = 10;
714 if v.len() <= MAX_INSERTION {
715 insertion_sort(v, is_less);
720 let (pivot, _) = choose_pivot(v, is_less);
722 // If the chosen pivot is equal to the predecessor, then it's the smallest element in the
723 // slice. Partition the slice into elements equal to and elements greater than the pivot.
724 // This case is usually hit when the slice contains many duplicate elements.
725 if let Some(p) = pred {
726 if !is_less(p, &v[pivot]) {
727 let mid = partition_equal(v, pivot, is_less);
729 // If we've passed our index, then we're good.
734 // Otherwise, continue sorting elements greater than the pivot.
742 let (mid, _) = partition(v, pivot, is_less);
744 // Split the slice into `left`, `pivot`, and `right`.
745 let (left, right) = { v }.split_at_mut(mid);
746 let (pivot, right) = right.split_at_mut(1);
747 let pivot = &pivot[0];
751 index = index - mid - 1;
753 } else if mid > index {
756 // If mid == index, then we're done, since partition() guaranteed that all elements
757 // after mid are greater than or equal to mid.
763 pub fn partition_at_index<T, F>(
767 ) -> (&mut [T], &mut T, &mut [T])
769 F: FnMut(&T, &T) -> bool,
771 use cmp::Ordering::Greater;
772 use cmp::Ordering::Less;
774 if index >= v.len() {
775 panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
778 if mem::size_of::<T>() == 0 {
779 // Sorting has no meaningful behavior on zero-sized types. Do nothing.
780 } else if index == v.len() - 1 {
781 // Find max element and place it in the last position of the array. We're free to use
782 // `unwrap()` here because we know v must not be empty.
783 let (max_index, _) = v
786 .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
788 v.swap(max_index, index);
789 } else if index == 0 {
790 // Find min element and place it in the first position of the array. We're free to use
791 // `unwrap()` here because we know v must not be empty.
792 let (min_index, _) = v
795 .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
797 v.swap(min_index, index);
799 partition_at_index_loop(v, index, &mut is_less, None);
802 let (left, right) = v.split_at_mut(index);
803 let (pivot, right) = right.split_at_mut(1);
804 let pivot = &mut pivot[0];