]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice/sort.rs
Add some type-alias-impl-trait regression tests
[rust.git] / src / libcore / slice / sort.rs
1 //! Slice sorting
2 //!
3 //! This module contains an sort 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         unsafe {
24             ptr::copy_nonoverlapping(self.src, self.dest, 1);
25         }
26     }
27 }
28
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)
31 where
32     F: FnMut(&T, &T) -> bool,
33 {
34     let len = v.len();
35     unsafe {
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
40             // into the slice.
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);
44
45             for i in 2..len {
46                 if !is_less(v.get_unchecked(i), &*tmp) {
47                     break;
48                 }
49
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);
53             }
54             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
55         }
56     }
57 }
58
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)
61 where
62     F: FnMut(&T, &T) -> bool,
63 {
64     let len = v.len();
65     unsafe {
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
70             // into the slice.
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);
74
75             for i in (0..len - 2).rev() {
76                 if !is_less(&*tmp, v.get_unchecked(i)) {
77                     break;
78                 }
79
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);
83             }
84             // `hole` gets dropped and thus copies `tmp` into the remaining hole in `v`.
85         }
86     }
87 }
88
89 /// Partially sorts a slice by shifting several out-of-order elements around.
90 ///
91 /// Returns `true` if the slice is sorted at the end. This function is `O(n)` worst-case.
92 #[cold]
93 fn partial_insertion_sort<T, F>(v: &mut [T], is_less: &mut F) -> bool
94 where
95     F: FnMut(&T, &T) -> bool,
96 {
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;
101
102     let len = v.len();
103     let mut i = 1;
104
105     for _ in 0..MAX_STEPS {
106         unsafe {
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)) {
109                 i += 1;
110             }
111         }
112
113         // Are we done?
114         if i == len {
115             return true;
116         }
117
118         // Don't shift elements on short arrays, that has a performance cost.
119         if len < SHORTEST_SHIFTING {
120             return false;
121         }
122
123         // Swap the found pair of elements. This puts them in correct order.
124         v.swap(i - 1, i);
125
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);
130     }
131
132     // Didn't manage to sort the slice in the limited number of steps.
133     false
134 }
135
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)
138 where
139     F: FnMut(&T, &T) -> bool,
140 {
141     for i in 1..v.len() {
142         shift_tail(&mut v[..i + 1], is_less);
143     }
144 }
145
146 /// Sorts `v` using heapsort, which guarantees `O(n log n)` worst-case.
147 #[cold]
148 pub fn heapsort<T, F>(v: &mut [T], is_less: &mut F)
149 where
150     F: FnMut(&T, &T) -> bool,
151 {
152     // This binary heap respects the invariant `parent >= child`.
153     let mut sift_down = |v: &mut [T], mut node| {
154         loop {
155             // Children of `node`:
156             let left = 2 * node + 1;
157             let right = 2 * node + 2;
158
159             // Choose the greater child.
160             let greater =
161                 if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
162
163             // Stop if the invariant holds at `node`.
164             if greater >= v.len() || !is_less(&v[node], &v[greater]) {
165                 break;
166             }
167
168             // Swap `node` with the greater child, move one step down, and continue sifting.
169             v.swap(node, greater);
170             node = greater;
171         }
172     };
173
174     // Build the heap in linear time.
175     for i in (0..v.len() / 2).rev() {
176         sift_down(v, i);
177     }
178
179     // Pop maximal elements from the heap.
180     for i in (1..v.len()).rev() {
181         v.swap(0, i);
182         sift_down(&mut v[..i], 0);
183     }
184 }
185
186 /// Partitions `v` into elements smaller than `pivot`, followed by elements greater than or equal
187 /// to `pivot`.
188 ///
189 /// Returns the number of elements smaller than `pivot`.
190 ///
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.
193 ///
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
196 where
197     F: FnMut(&T, &T) -> bool,
198 {
199     // Number of elements in a typical block.
200     const BLOCK: usize = 128;
201
202     // The partitioning algorithm repeats the following steps until completion:
203     //
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.
207     //
208     // We keep the following variables for a block of elements:
209     //
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.
214
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];
221
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];
228
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.
231
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>()
236     }
237
238     loop {
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;
242
243         if is_done {
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 {
247                 rem -= BLOCK;
248             }
249
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.
252             if start_l < end_l {
253                 block_r = rem;
254             } else if start_r < end_r {
255                 block_l = rem;
256             } else {
257                 block_l = rem / 2;
258                 block_r = rem - block_l;
259             }
260             debug_assert!(block_l <= BLOCK && block_r <= BLOCK);
261             debug_assert!(width(l, r) == block_l + block_r);
262         }
263
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);
268             let mut elem = l;
269
270             for i in 0..block_l {
271                 unsafe {
272                     // Branchless comparison.
273                     *end_l = i as u8;
274                     end_l = end_l.offset(!is_less(&*elem, pivot) as isize);
275                     elem = elem.offset(1);
276                 }
277             }
278         }
279
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);
284             let mut elem = r;
285
286             for i in 0..block_r {
287                 unsafe {
288                     // Branchless comparison.
289                     elem = elem.offset(-1);
290                     *end_r = i as u8;
291                     end_r = end_r.offset(is_less(&*elem, pivot) as isize);
292                 }
293             }
294         }
295
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));
298
299         if count > 0 {
300             macro_rules! left {
301                 () => {
302                     l.offset(*start_l as isize)
303                 };
304             }
305             macro_rules! right {
306                 () => {
307                     r.offset(-(*start_r as isize) - 1)
308                 };
309             }
310
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.
314             unsafe {
315                 let tmp = ptr::read(left!());
316                 ptr::copy_nonoverlapping(right!(), left!(), 1);
317
318                 for _ in 1..count {
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);
323                 }
324
325                 ptr::copy_nonoverlapping(&tmp, right!(), 1);
326                 mem::forget(tmp);
327                 start_l = start_l.offset(1);
328                 start_r = start_r.offset(1);
329             }
330         }
331
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) };
335         }
336
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)) };
340         }
341
342         if is_done {
343             break;
344         }
345     }
346
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.
350
351     if start_l < end_l {
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 {
356             unsafe {
357                 end_l = end_l.offset(-1);
358                 ptr::swap(l.offset(*end_l as isize), r.offset(-1));
359                 r = r.offset(-1);
360             }
361         }
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 {
368             unsafe {
369                 end_r = end_r.offset(-1);
370                 ptr::swap(l, r.offset(-(*end_r as isize) - 1));
371                 l = l.offset(1);
372             }
373         }
374         width(v.as_mut_ptr(), l)
375     } else {
376         // Nothing else to do, we're done.
377         width(v.as_mut_ptr(), l)
378     }
379 }
380
381 /// Partitions `v` into elements smaller than `v[pivot]`, followed by elements greater than or
382 /// equal to `v[pivot]`.
383 ///
384 /// Returns a tuple of:
385 ///
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)
389 where
390     F: FnMut(&T, &T) -> bool,
391 {
392     let (mid, was_partitioned) = {
393         // Place the pivot at the beginning of slice.
394         v.swap(0, pivot);
395         let (pivot, v) = v.split_at_mut(1);
396         let pivot = &mut pivot[0];
397
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 };
402         let pivot = &*tmp;
403
404         // Find the first pair of out-of-order elements.
405         let mut l = 0;
406         let mut r = v.len();
407         unsafe {
408             // Find the first element greater then or equal to the pivot.
409             while l < r && is_less(v.get_unchecked(l), pivot) {
410                 l += 1;
411             }
412
413             // Find the last element smaller that the pivot.
414             while l < r && !is_less(v.get_unchecked(r - 1), pivot) {
415                 r -= 1;
416             }
417         }
418
419         (l + partition_in_blocks(&mut v[l..r], pivot, is_less), l >= r)
420
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
423         // safety!
424     };
425
426     // Place the pivot between the two partitions.
427     v.swap(0, mid);
428
429     (mid, was_partitioned)
430 }
431
432 /// Partitions `v` into elements equal to `v[pivot]` followed by elements greater than `v[pivot]`.
433 ///
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
437 where
438     F: FnMut(&T, &T) -> bool,
439 {
440     // Place the pivot at the beginning of slice.
441     v.swap(0, pivot);
442     let (pivot, v) = v.split_at_mut(1);
443     let pivot = &mut pivot[0];
444
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 };
449     let pivot = &*tmp;
450
451     // Now partition the slice.
452     let mut l = 0;
453     let mut r = v.len();
454     loop {
455         unsafe {
456             // Find the first element greater that the pivot.
457             while l < r && !is_less(pivot, v.get_unchecked(l)) {
458                 l += 1;
459             }
460
461             // Find the last element equal to the pivot.
462             while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
463                 r -= 1;
464             }
465
466             // Are we done?
467             if l >= r {
468                 break;
469             }
470
471             // Swap the found pair of out-of-order elements.
472             r -= 1;
473             ptr::swap(v.get_unchecked_mut(l), v.get_unchecked_mut(r));
474             l += 1;
475         }
476     }
477
478     // We found `l` elements equal to the pivot. Add 1 to account for the pivot itself.
479     l + 1
480
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!
483 }
484
485 /// Scatters some elements around in an attempt to break patterns that might cause imbalanced
486 /// partitions in quicksort.
487 #[cold]
488 fn break_patterns<T>(v: &mut [T]) {
489     let len = v.len();
490     if len >= 8 {
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;
497             random
498         };
499         let mut gen_usize = || {
500             if mem::size_of::<usize>() <= 4 {
501                 gen_u32() as usize
502             } else {
503                 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
504             }
505         };
506
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();
510
511         // Some pivot candidates will be in the nearby of this index. Let's randomize them.
512         let pos = len / 4 * 2;
513
514         for i in 0..3 {
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);
519
520             // `other` is guaranteed to be less than `2 * len`.
521             if other >= len {
522                 other -= len;
523             }
524
525             v.swap(pos - 1 + i, other);
526         }
527     }
528 }
529
530 /// Chooses a pivot in `v` and returns the index and `true` if the slice is likely already sorted.
531 ///
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)
534 where
535     F: FnMut(&T, &T) -> bool,
536 {
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;
542
543     let len = v.len();
544
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;
549
550     // Counts the total number of swaps we are about to perform while sorting indices.
551     let mut swaps = 0;
552
553     if len >= 8 {
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)) {
557                 ptr::swap(a, b);
558                 swaps += 1;
559             }
560         };
561
562         // Swaps indices so that `v[a] <= v[b] <= v[c]`.
563         let mut sort3 = |a: &mut usize, b: &mut usize, c: &mut usize| {
564             sort2(a, b);
565             sort2(b, c);
566             sort2(a, b);
567         };
568
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| {
572                 let tmp = *a;
573                 sort3(&mut (tmp - 1), a, &mut (tmp + 1));
574             };
575
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);
580         }
581
582         // Find the median among `a`, `b`, and `c`.
583         sort3(&mut a, &mut b, &mut c);
584     }
585
586     if swaps < MAX_SWAPS {
587         (b, swaps == 0)
588     } else {
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.
591         v.reverse();
592         (len - 1 - b, true)
593     }
594 }
595
596 /// Sorts `v` recursively.
597 ///
598 /// If the slice had a predecessor in the original array, it is specified as `pred`.
599 ///
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)
603 where
604     F: FnMut(&T, &T) -> bool,
605 {
606     // Slices of up to this length get sorted using insertion sort.
607     const MAX_INSERTION: usize = 20;
608
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;
613
614     loop {
615         let len = v.len();
616
617         // Very short slices get sorted using insertion sort.
618         if len <= MAX_INSERTION {
619             insertion_sort(v, is_less);
620             return;
621         }
622
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.
625         if limit == 0 {
626             heapsort(v, is_less);
627             return;
628         }
629
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.
632         if !was_balanced {
633             break_patterns(v);
634             limit -= 1;
635         }
636
637         // Choose a pivot and try guessing whether the slice is already sorted.
638         let (pivot, likely_sorted) = choose_pivot(v, is_less);
639
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) {
646                 return;
647             }
648         }
649
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);
656
657                 // Continue sorting elements greater than the pivot.
658                 v = &mut { v }[mid..];
659                 continue;
660             }
661         }
662
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;
667
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];
672
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);
678             v = right;
679             pred = Some(pivot);
680         } else {
681             recurse(right, is_less, Some(pivot), limit);
682             v = left;
683         }
684     }
685 }
686
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)
689 where
690     F: FnMut(&T, &T) -> bool,
691 {
692     // Sorting has no meaningful behavior on zero-sized types.
693     if mem::size_of::<T>() == 0 {
694         return;
695     }
696
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;
699
700     recurse(v, &mut is_less, None, limit);
701 }
702
703 fn partition_at_index_loop<'a, T, F>(
704     mut v: &'a mut [T],
705     mut index: usize,
706     is_less: &mut F,
707     mut pred: Option<&'a T>,
708 ) where
709     F: FnMut(&T, &T) -> bool,
710 {
711     loop {
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);
716             return;
717         }
718
719         // Choose a pivot
720         let (pivot, _) = choose_pivot(v, is_less);
721
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);
728
729                 // If we've passed our index, then we're good.
730                 if mid > index {
731                     return;
732                 }
733
734                 // Otherwise, continue sorting elements greater than the pivot.
735                 v = &mut v[mid..];
736                 index = index - mid;
737                 pred = None;
738                 continue;
739             }
740         }
741
742         let (mid, _) = partition(v, pivot, is_less);
743
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];
748
749         if mid < index {
750             v = right;
751             index = index - mid - 1;
752             pred = Some(pivot);
753         } else if mid > index {
754             v = left;
755         } else {
756             // If mid == index, then we're done, since partition() guaranteed that all elements
757             // after mid are greater than or equal to mid.
758             return;
759         }
760     }
761 }
762
763 pub fn partition_at_index<T, F>(
764     v: &mut [T],
765     index: usize,
766     mut is_less: F,
767 ) -> (&mut [T], &mut T, &mut [T])
768 where
769     F: FnMut(&T, &T) -> bool,
770 {
771     use cmp::Ordering::Greater;
772     use cmp::Ordering::Less;
773
774     if index >= v.len() {
775         panic!("partition_at_index index {} greater than length of slice {}", index, v.len());
776     }
777
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
784             .iter()
785             .enumerate()
786             .max_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
787             .unwrap();
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
793             .iter()
794             .enumerate()
795             .min_by(|&(_, x), &(_, y)| if is_less(x, y) { Less } else { Greater })
796             .unwrap();
797         v.swap(min_index, index);
798     } else {
799         partition_at_index_loop(v, index, &mut is_less, None);
800     }
801
802     let (left, right) = v.split_at_mut(index);
803     let (pivot, right) = right.split_at_mut(1);
804     let pivot = &mut pivot[0];
805     (left, pivot, right)
806 }