]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/sort.rs
Rollup merge of #74561 - RalfJung:backtrace, r=alexcrichton
[rust.git] / src / libcore / slice / sort.rs
1 //! Slice sorting
2 //!
3 //! This module contains a sorting algorithm based on Orson Peters' pattern-defeating quicksort,
4 //! published at: https://github.com/orlp/pdqsort
5 //!
6 //! Unstable sorting is compatible with libcore because it doesn't allocate memory, unlike our
7 //! stable sorting implementation.
8
9 // ignore-tidy-undocumented-unsafe
10
11 use crate::cmp;
12 use crate::mem::{self, MaybeUninit};
13 use crate::ptr;
14
15 /// When dropped, copies from `src` into `dest`.
16 struct CopyOnDrop<T> {
17     src: *mut T,
18     dest: *mut T,
19 }
20
21 impl<T> Drop for CopyOnDrop<T> {
22     fn drop(&mut self) {
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`.
26         unsafe {
27             ptr::copy_nonoverlapping(self.src, self.dest, 1);
28         }
29     }
30 }
31
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)
34 where
35     F: FnMut(&T, &T) -> bool,
36 {
37     let len = v.len();
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`).
40     //
41     // a. Indexing:
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.
44     //
45     // b. Memory copying
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.
51     //
52     // See comments below for further detail.
53     unsafe {
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
58             // into the slice.
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);
62
63             for i in 2..len {
64                 if !is_less(v.get_unchecked(i), &*tmp) {
65                     break;
66                 }
67
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);
71             }
72             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
73         }
74     }
75 }
76
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)
79 where
80     F: FnMut(&T, &T) -> bool,
81 {
82     let len = v.len();
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`).
85     //
86     // a. Indexing:
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.
89     //
90     // b. Memory copying
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.
96     //
97     // See comments below for further detail.
98     unsafe {
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
103             // into the slice.
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);
107
108             for i in (0..len - 2).rev() {
109                 if !is_less(&*tmp, v.get_unchecked(i)) {
110                     break;
111                 }
112
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);
116             }
117             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
118         }
119     }
120 }
121
122 /// Partially sorts a slice by shifting several out-of-order elements around.
123 ///
124 /// Returns `true` if the slice is sorted at the end. This function is *O*(*n*) worst-case.
125 #[cold]
126 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
127 where
128     F: FnMut(&T, &T) -> bool,
129 {
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;
134
135     let len = v.len();
136     let mut i = 1;
137
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`
141         unsafe {
142             // Find the next pair of adjacent out-of-order elements.
143             while i < len && !is_less(v.get_unchecked(i), v.get_unchecked(i - 1)) {
144                 i += 1;
145             }
146         }
147
148         // Are we done?
149         if i == len {
150             return true;
151         }
152
153         // Don't shift elements on short arrays, that has a performance cost.
154         if len < SHORTEST_SHIFTING {
155             return false;
156         }
157
158         // Swap the found pair of elements. This puts them in correct order.
159         v.swap(i - 1, i);
160
161         // Shift the smaller element to the left.
162         shift_tail(&mut v[..i], is_less);
163         // Shift the greater element to the right.
164         shift_head(&mut v[i..], is_less);
165     }
166
167     // Didn't manage to sort the slice in the limited number of steps.
168     false
169 }
170
171 /// Sorts a slice using insertion sort, which is *O*(*n*^2) worst-case.
172 fn insertion_sort<T, F>(v: &mut [T], is_less: &mut F)
173 where
174     F: FnMut(&T, &T) -> bool,
175 {
176     for i in 1..v.len() {
177         shift_tail(&mut v[..i + 1], is_less);
178     }
179 }
180
181 /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case.
182 #[cold]
183 pub fn heapsort<T, F>(v: &mut [T], is_less: &mut F)
184 where
185     F: FnMut(&T, &T) -> bool,
186 {
187     // This binary heap respects the invariant `parent >= child`.
188     let mut sift_down = |v: &mut [T], mut node| {
189         loop {
190             // Children of `node`:
191             let left = 2 * node + 1;
192             let right = 2 * node + 2;
193
194             // Choose the greater child.
195             let greater =
196                 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
197
198             // Stop if the invariant holds at `node`.
199             if greater >= v.len() || !is_less(&v[node], &v[greater]) {
200                 break;
201             }
202
203             // Swap `node` with the greater child, move one step down, and continue sifting.
204             v.swap(node, greater);
205             node = greater;
206         }
207     };
208
209     // Build the heap in linear time.
210     for i in (0..v.len() / 2).rev() {
211         sift_down(v, i);
212     }
213
214     // Pop maximal elements from the heap.
215     for i in (1..v.len()).rev() {
216         v.swap(0, i);
217         sift_down(&mut v[..i], 0);
218     }
219 }
220
221 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
222 /// to `pivot`.
223 ///
224 /// Returns the number of elements smaller than `pivot`.
225 ///
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.
228 ///
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
231 where
232     F: FnMut(&T, &T) -> bool,
233 {
234     // Number of elements in a typical block.
235     const BLOCK: usize = 128;
236
237     // The partitioning algorithm repeats the following steps until completion:
238     //
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.
242     //
243     // We keep the following variables for a block of elements:
244     //
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.
249
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];
256
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];
264
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.
267
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>()
272     }
273
274     loop {
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;
278
279         if is_done {
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 {
283                 rem -= BLOCK;
284             }
285
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.
288             if start_l < end_l {
289                 block_r = rem;
290             } else if start_r < end_r {
291                 block_l = rem;
292             } else {
293                 block_l = rem / 2;
294                 block_r = rem - block_l;
295             }
296             debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
297             debug_assert!(width(l, r) == block_l + block_r);
298         }
299
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);
304             let mut elem = l;
305
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.
317                 unsafe {
318                     // Branchless comparison.
319                     *end_l = i as u8;
320                     end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
321                     elem = elem.offset(1);
322                 }
323             }
324         }
325
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);
330             let mut elem = r;
331
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.
344                 unsafe {
345                     // Branchless comparison.
346                     elem = elem.offset(-1);
347                     *end_r = i as u8;
348                     end_r = end_r.offset(is_less(&*elem, pivot) as isize);
349                 }
350             }
351         }
352
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));
355
356         if count > 0 {
357             macro_rules! left {
358                 () => {
359                     l.offset(*start_l as isize)
360                 };
361             }
362             macro_rules! right {
363                 () => {
364                     r.offset(-(*start_r as isize) - 1)
365                 };
366             }
367
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.
371             unsafe {
372                 let tmp = ptr::read(left!());
373                 ptr::copy_nonoverlapping(right!(), left!(), 1);
374
375                 for _ in 1..count {
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);
380                 }
381
382                 ptr::copy_nonoverlapping(&tmp, right!(), 1);
383                 mem::forget(tmp);
384                 start_l = start_l.offset(1);
385                 start_r = start_r.offset(1);
386             }
387         }
388
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) };
392         }
393
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)) };
397         }
398
399         if is_done {
400             break;
401         }
402     }
403
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.
407
408     if start_l < end_l {
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 {
413             unsafe {
414                 end_l = end_l.offset(-1);
415                 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
416                 r = r.offset(-1);
417             }
418         }
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 {
425             unsafe {
426                 end_r = end_r.offset(-1);
427                 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
428                 l = l.offset(1);
429             }
430         }
431         width(v.as_mut_ptr(), l)
432     } else {
433         // Nothing else to do, we're done.
434         width(v.as_mut_ptr(), l)
435     }
436 }
437
438 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
439 /// equal to `v[pivot]`.
440 ///
441 /// Returns a tuple of:
442 ///
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)
446 where
447     F: FnMut(&T, &T) -> bool,
448 {
449     let (mid, was_partitioned) = {
450         // Place the pivot at the beginning of slice.
451         v.swap(0, pivot);
452         let (pivot, v) = v.split_at_mut(1);
453         let pivot = &mut pivot[0];
454
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 };
459         let pivot = &*tmp;
460
461         // Find the first pair of out-of-order elements.
462         let mut l = 0;
463         let mut r = v.len();
464
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.
469         unsafe {
470             // Find the first element greater than or equal to the pivot.
471             while l < r && is_less(v.get_unchecked(l), pivot) {
472                 l += 1;
473             }
474
475             // Find the last element smaller that the pivot.
476             while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
477                 r -= 1;
478             }
479         }
480
481         (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
482
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
485         // safety!
486     };
487
488     // Place the pivot between the two partitions.
489     v.swap(0, mid);
490
491     (mid, was_partitioned)
492 }
493
494 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
495 ///
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
499 where
500     F: FnMut(&T, &T) -> bool,
501 {
502     // Place the pivot at the beginning of slice.
503     v.swap(0, pivot);
504     let (pivot, v) = v.split_at_mut(1);
505     let pivot = &mut pivot[0];
506
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 };
512     let pivot = &*tmp;
513
514     // Now partition the slice.
515     let mut l = 0;
516     let mut r = v.len();
517     loop {
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.
522         unsafe {
523             // Find the first element greater than the pivot.
524             while l < r && !is_less(pivot, v.get_unchecked(l)) {
525                 l += 1;
526             }
527
528             // Find the last element equal to the pivot.
529             while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
530                 r -= 1;
531             }
532
533             // Are we done?
534             if l >= r {
535                 break;
536             }
537
538             // Swap the found pair of out-of-order elements.
539             r -= 1;
540             ptr::swap(v.get_unchecked_mut(l), v.get_unchecked_mut(r));
541             l += 1;
542         }
543     }
544
545     // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
546     l + 1
547
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!
550 }
551
552 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
553 /// partitions in quicksort.
554 #[cold]
555 fn break_patterns<T>(v: &mut [T]) {
556     let len = v.len();
557     if len >= 8 {
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;
564             random
565         };
566         let mut gen_usize = || {
567             if mem::size_of::<usize>() <= 4 {
568                 gen_u32() as usize
569             } else {
570                 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
571             }
572         };
573
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();
577
578         // Some pivot candidates will be in the nearby of this index. Let's randomize them.
579         let pos = len / 4 * 2;
580
581         for i in 0..3 {
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);
586
587             // `other` is guaranteed to be less than `2 * len`.
588             if other >= len {
589                 other -= len;
590             }
591
592             v.swap(pos - 1 + i, other);
593         }
594     }
595 }
596
597 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
598 ///
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)
601 where
602     F: FnMut(&T, &T) -> bool,
603 {
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;
609
610     let len = v.len();
611
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;
616
617     // Counts the total number of swaps we are about to perform while sorting indices.
618     let mut swaps = 0;
619
620     if len >= 8 {
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)) {
624                 ptr::swap(a, b);
625                 swaps += 1;
626             }
627         };
628
629         // Swaps indices so that `v[a] <= v[b] <= v[c]`.
630         let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
631             sort2(a, b);
632             sort2(b, c);
633             sort2(a, b);
634         };
635
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| {
639                 let tmp = *a;
640                 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
641             };
642
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);
647         }
648
649         // Find the median among `a`, `b`, and `c`.
650         sort3(&mut a, &mut b, &mut c);
651     }
652
653     if swaps < MAX_SWAPS {
654         (b, swaps == 0)
655     } else {
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.
658         v.reverse();
659         (len - 1 - b, true)
660     }
661 }
662
663 /// Sorts `v` recursively.
664 ///
665 /// If the slice had a predecessor in the original array, it is specified as `pred`.
666 ///
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)
670 where
671     F: FnMut(&T, &T) -> bool,
672 {
673     // Slices of up to this length get sorted using insertion sort.
674     const MAX_INSERTION: usize = 20;
675
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;
680
681     loop {
682         let len = v.len();
683
684         // Very short slices get sorted using insertion sort.
685         if len <= MAX_INSERTION {
686             insertion_sort(v, is_less);
687             return;
688         }
689
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.
692         if limit == 0 {
693             heapsort(v, is_less);
694             return;
695         }
696
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.
699         if !was_balanced {
700             break_patterns(v);
701             limit -= 1;
702         }
703
704         // Choose a pivot and try guessing whether the slice is already sorted.
705         let (pivot, likely_sorted) = choose_pivot(v, is_less);
706
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) {
713                 return;
714             }
715         }
716
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);
723
724                 // Continue sorting elements greater than the pivot.
725                 v = &mut { v }[mid..];
726                 continue;
727             }
728         }
729
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;
734
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];
739
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);
745             v = right;
746             pred = Some(pivot);
747         } else {
748             recurse(right, is_less, Some(pivot), limit);
749             v = left;
750         }
751     }
752 }
753
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)
756 where
757     F: FnMut(&T, &T) -> bool,
758 {
759     // Sorting has no meaningful behavior on zero-sized types.
760     if mem::size_of::<T>() == 0 {
761         return;
762     }
763
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;
766
767     recurse(v, &mut is_less, None, limit);
768 }
769
770 fn partition_at_index_loop<'a, T, F>(
771     mut v: &'a mut [T],
772     mut index: usize,
773     is_less: &mut F,
774     mut pred: Option<&'a T>,
775 ) where
776     F: FnMut(&T, &T) -> bool,
777 {
778     loop {
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);
783             return;
784         }
785
786         // Choose a pivot
787         let (pivot, _) = choose_pivot(v, is_less);
788
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);
795
796                 // If we've passed our index, then we're good.
797                 if mid > index {
798                     return;
799                 }
800
801                 // Otherwise, continue sorting elements greater than the pivot.
802                 v = &mut v[mid..];
803                 index = index - mid;
804                 pred = None;
805                 continue;
806             }
807         }
808
809         let (mid, _) = partition(v, pivot, is_less);
810
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];
815
816         if mid < index {
817             v = right;
818             index = index - mid - 1;
819             pred = Some(pivot);
820         } else if mid > index {
821             v = left;
822         } else {
823             // If mid == index, then we're done, since partition() guaranteed that all elements
824             // after mid are greater than or equal to mid.
825             return;
826         }
827     }
828 }
829
830 pub fn partition_at_index<T, F>(
831     v: &mut [T],
832     index: usize,
833     mut is_less: F,
834 ) -> (&mut [T], &mut T, &mut [T])
835 where
836     F: FnMut(&T, &T) -> bool,
837 {
838     use cmp::Ordering::Greater;
839     use cmp::Ordering::Less;
840
841     if index >= v.len() {
842         panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
843     }
844
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
851             .iter()
852             .enumerate()
853             .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
854             .unwrap();
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
860             .iter()
861             .enumerate()
862             .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
863             .unwrap();
864         v.swap(min_index, index);
865     } else {
866         partition_at_index_loop(v, index, &mut is_less, None);
867     }
868
869     let (left, right) = v.split_at_mut(index);
870     let (pivot, right) = right.split_at_mut(1);
871     let pivot = &mut pivot[0];
872     (left, pivot, right)
873 }