1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use ManuallyDrop;
use ptr;
use heap;
/// Sorts a slice in place using intro sort.
///
/// Intro sort (introspective sort), designed by David Musser in 1997, is a quick sort that
/// watches its own progress. Quick sort partitions the slice around a pivot and sorts the two
/// parts the same way; with good pivots each level of partitioning halves the parts and the
/// sort makes `O(n log n)` comparisons, but no cheap pivot rule is good on every input, and
/// bad pivots make it quadratic. Intro sort counts the levels: a part still being partitioned
/// after `2·⌊log₂ n⌋` levels is handed to heap sort, which is `O(n log n)` on every input, so
/// the whole sort is too, while typical input never reaches the limit and keeps quick sort's
/// speed. Short parts are left to insertion sort.
///
/// Five refinements keep the algorithm as cheap as intro sort can be, and its comparisons the
/// same as Hoare's:
///
/// * **Sorted and reverse-sorted input is recognised.** The slice is first scanned for one
/// ascending or strictly descending run; if it covers the whole slice, the slice is left
/// alone or reversed. This costs `n − 1` comparisons on such input and usually two or three
/// on any other.
/// * **Branchless block partitioning.** Hoare's scheme scans from both ends for elements on
/// the wrong side of the pivot and swaps them; each scan stops at an unpredictable element,
/// a mispredicted branch. Here each end compares a block of 128 elements first, recording
/// the misplaced ones by offset without branching, and then exchanges as many misplaced
/// pairs as both blocks have (Edelkamp and Weiss's BlockQuicksort). It makes the same
/// comparisons as Hoare's scheme and exchanges each pair in a cycle of two moves instead of
/// a swap's three. On random input this is 1.8–2.7 times faster than Hoare's scans for
/// integers, 1.7–2.2 times for strings and 1.4–2.1 times for 64-byte elements. The block
/// scans are unrolled by 8, another 1.03–1.08 times on random input and 1.1–1.25 times on
/// nearly sorted input, where the scans are nearly all the work.
/// * **Equal keys split evenly.** As in Hoare's and Musser's scheme, an element equal to the
/// pivot stops the scans on both sides, so equal keys are spread over both parts: input with
/// few distinct keys, even all equal but one, costs `O(n log n)` like any other, without
/// ever reaching the depth limit.
/// * **Pivots away from the ends, from a ninther on long parts.** The pivot is the median of
/// the elements at a quarter, half and three quarters of the part, and from 128 elements on
/// the median of three medians of three spread over it (Tukey's ninther), which is closer to
/// the true median. Musser samples the first, middle and last elements instead, which on
/// sorted input with a few elements appended keeps choosing the second smallest element as
/// the pivot until the depth limit gives up: quartiles are 1.2–4 times faster there.
/// * **Insertion sort while the part is fresh.** Parts of at most 24 elements are insertion
/// sorted as soon as partitioning leaves them, while they are still in the cache. Musser
/// leaves them all for one insertion pass over the whole slice at the end, which makes the
/// same comparisons but reads the whole slice once more: 1.05–1.15 times slower for strings.
///
/// The recursion goes into the smaller part only and loops on the larger one, so the stack
/// never holds more than `log₂ n` frames.
///
/// # Properties
///
/// * **Unstable**: equal elements may be reordered.
/// * **In place**: no allocation, `O(log n)` stack.
/// * **Adaptive** to sorted and reverse-sorted input; nearly sorted input is cheap too, since
/// Hoare's scheme moves only misplaced elements.
///
/// | Case | Comparisons | Moves |
/// |-----------------------------------|---------------------------------|--------------------|
/// | Best (sorted, reverse, all equal) | `n − 1` | `0` (`n` reversed) |
/// | Average (random) | `≈ (1.1–1.19)·n·log₂ n` | `O(n log n)` |
/// | Worst | `O(n log n)` | `O(n log n)` |
///
/// For `n = 1000`: 999 comparisons on sorted or reverse-sorted input, about 6,800 with 10
/// random pairs swapped and about 11,800 on random input. Insertion into parts of up to 24
/// elements costs more comparisons than partitioning them further would, but less time. With
/// `k` distinct keys the cost stays about `0.85·n·log₂ n`: unlike this crate's
/// [`quick`](crate::sort::quick) sort, intro sort does not take all copies of the pivot out at
/// once. McIlroy's adversary, which answers comparisons so as to make every pivot bad, drives
/// the partitioning alone to 9.1 million comparisons for `n = 10,000`; the heap sort fallback
/// keeps the whole sort at about 470,000.
///
/// Against this crate's [`quick`](crate::sort::quick) sort, which also falls back to heap sort
/// but partitions elements of up to 64 bytes by Lomuto's scheme without branching, sorts short
/// parts by sorting networks and takes all copies of a pivot out at once: 1.35–1.55 times
/// slower on random integers from 1000 elements on, 1.06–1.13 times on random strings and
/// 1.5–3.8 times with few distinct keys; but 1.2–1.65 times faster on random 64-byte elements,
/// which block partitioning moves only when misplaced instead of twice each, and 1.3–3.6 times
/// faster on nearly sorted input.
/// Against [`slice::sort_unstable`]: 1.45–1.75 times slower on random integers and within 1.07
/// times on random strings, but 1.08–1.55 times faster on random 64-byte elements and 1.5–3.7
/// times on nearly sorted input of 100 elements or more. Against [`heap`](fn@heap) sort, which
/// it falls back to, it is 1.3–2.4 times faster on random integers, 2.1–6.7 times on strings
/// and 1.5–4.4 times on 64-byte elements.
///
/// Prefer [`slice::sort_unstable`] for real workloads.
///
/// # Panics
///
/// Does not panic by itself. If the [`Ord`] implementation of `T` panics, the panic is
/// propagated and `arr` is left in an unspecified order, but it still holds every original
/// element exactly once: nothing is dropped twice or leaked. An [`Ord`] that is not a total
/// order leaves `arr` in an unspecified order with every element exactly once as well.
///
/// # Examples
///
/// ```
/// use a::sort::intro;
///
/// let mut v = [5, 1, 4, 2, 8, 0, 3, 9, 7, 6];
/// intro(&mut v);
/// assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
///
/// // Equal keys split evenly between the parts.
/// let mut v: Vec<u8> = (0..1000).map(|i| (i * 7 % 3) as u8).collect();
/// intro(&mut v);
/// assert!(v.windows(2).all(|w| w[0] <= w[1]));
///
/// let mut words = vec!["pear", "apple", "fig"];
/// intro(&mut words);
/// assert_eq!(words, ["apple", "fig", "pear"]);
/// ```
/// Parts of at most this many elements are sorted by insertion instead of partitioned.
///
/// Measured against 16, Musser's choice: as fast on random input, and 1.05–1.45 times faster
/// on nearly sorted input, few distinct keys and short sawtooth slices. Against 32: 1.03–1.06
/// times faster on random strings of up to 1000 elements, but up to 1.1 times slower with few
/// distinct keys for 64-byte elements. For elements of at most 8 bytes, this crate's merge
/// sort's branchless short-run sort would be 1.1–1.4 times faster than insertion on random
/// slices of up to 100 elements, but 1.1–1.4 times slower on nearly sorted input and with
/// few distinct keys, whose short parts insertion sort barely has to move.
const SHORT: usize = 24;
/// From this length on, the pivot is the median of three medians of three (Tukey's ninther)
/// instead of the median of three.
///
/// Measured against the median of three throughout: 1.04–1.13 times faster on sawtooth input
/// of 100,000 elements or more, and up to 1.08 times on random input.
const NINTHER: usize = 128;
/// How many elements each side of [`partition_blocks`] compares before moving any; at most 256,
/// so that an offset into a block fits in a byte.
///
/// Edelkamp and Weiss's choice. Measured against 64: 1.02–1.06 times faster on random input
/// from 1000 elements on, and 1.02–1.07 times on nearly sorted input and few distinct keys;
/// 256 is no faster.
const BLOCK: usize = 128;
/// How many comparisons [`scan_block`] makes per round of its loop.
const SCAN_UNROLL: usize = 8;
/// Sorts `v`, falling back to heap sort once `limit` more levels of partitioning have not
/// finished the job.
/// Returns the index of the median of the elements at a quarter, half and three quarters of
/// `v`, or from [`NINTHER`] elements on of the median of the medians of three groups of three
/// spread over `v`.
///
/// Musser takes the first, middle and last elements. Swapping the pivot to the front then moves
/// the first element, the smallest on sorted stretches, into the middle of the part, where the
/// next level's sample finds it again: on sorted input with a few random elements appended, the
/// pivot is the second smallest element level after level until the depth limit gives up.
/// Quartiles leave the ends alone and are 1.2–4 times faster on such input, and no different on
/// any other.
/// Returns whichever of `a`, `b` and `c` indexes the median of the three elements, with two or
/// three comparisons.
/// Partitions `v` around the pivot `v[0]` and moves the pivot between the two parts. Returns
/// its index `mid`: no element of `v[..mid]` is greater than the pivot, and no element of
/// `v[mid + 1..]` smaller.
/// Partitions `v` around `pivot`, which is not in `v`, by Hoare's scheme without branching on
/// the comparisons (Edelkamp and Weiss's BlockQuicksort). Returns `mid`: no element of
/// `v[..mid]` is greater than the pivot, and no element of `v[mid..]` smaller.
///
/// Hoare's scheme scans from the left for an element that must not stay on the left, from the
/// right for one that must not stay on the right, and swaps the two; each scan stops at an
/// unpredictable element, a mispredicted branch. Here each side instead compares a whole block
/// of [`BLOCK`] elements first, writing the offset of every element and advancing a count by
/// whether it is misplaced, so the outcome selects an address instead of a branch; then as many
/// misplaced pairs as both blocks have are exchanged. A block whose misplaced elements have all
/// been exchanged is replaced by the next one; the last blocks share what is left.
///
/// Elements equal to the pivot count as misplaced on both sides, as in Hoare's and Musser's
/// scheme, so they are spread over both parts: all-equal input splits evenly instead of
/// degrading.
/// Writes the offsets `i < block` for which `misplaced(i)` holds into `offsets`, in order, and
/// returns how many there are. Every offset is written and the count advanced by the answer,
/// so the answer selects an address instead of a branch.
///
/// The loop is unrolled by [`SCAN_UNROLL`]: measured against no unrolling, 1.03–1.08 times faster
/// on random input and 1.1–1.25 times on nearly sorted input, where nearly nothing is
/// exchanged and the scans are all the work; against unrolling by 4, up to 1.03 times.
/// Sorts `v` by insertion sort: each element is carried left past the greater ones before it.
/// Inserts the last element of `v` into the sorted rest of it.
/// An element held outside a slice and the vacant slot it belongs in: dropping it, when the
/// insertion is done or a comparison panics, writes the element there.