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
use select_unpredictable;
use ;
use ptr;
use ;
/// Sorts a slice in place using cocktail shaker sort.
///
/// Cocktail shaker sort is bubble sort that alternates direction. A forward pass walks the
/// unsorted range from left to right, carrying the largest element seen so far towards the
/// end; a backward pass then walks it from right to left, carrying the smallest element seen
/// so far towards the front. Each pass leaves the elements beyond its last move in their final
/// places, so the unsorted range shrinks from both ends, and a pass that moves nothing ends
/// the sort.
///
/// Bubble sort moves a small element near the end (a "turtle") only one slot left per pass,
/// so a single one costs it `n - 1` passes. Here the next backward pass carries it all the way
/// to its place: `[1, 2, ..., n - 1, 0]` costs `3n - 6` comparisons (for `n ≥ 3`) instead of
/// the `n(n - 1)/2` of bubble sort. On random input it makes about a third fewer comparisons
/// than bubble sort (`≈ n²/3` against `≈ n²/2`); on reverse-sorted input both make
/// `n(n - 1)/2`.
///
/// Three refinements keep the algorithm as cheap as cocktail shaker sort can be:
///
/// * **Last-move tracking at both ends.** A forward pass ends the unsorted range at the last
/// element it moved, and a backward pass starts it just after the last element it moved, so
/// already-sorted input finishes after a single pass of `n - 1` comparisons and sorted runs
/// at either end are never rescanned.
/// * **Hole shifting instead of swapping.** An element travelling `k` slots is read once, the
/// `k` elements it overtakes are each shifted by one slot towards where it came from as
/// they are compared with it, and it is written once into its final slot: `k + 1` moves
/// instead of the `3k` moves of `k` swaps. Shifting while comparing, rather than finding the
/// distance first and moving a block afterwards, touches each element once and avoids a
/// `memmove` call per carry, most of which are only a slot or two long; on random `u64`
/// input that is about twice as fast.
/// * **Branchless passes for small elements.** Whether a comparison starts or ends a carry is
/// hard to predict on random input. For elements of at most 8 bytes with no drop glue, a
/// pass can instead hold the running extreme in a register and, at every comparison, write
/// the other element into the vacant slot behind it, with no branch on the outcome; an
/// element that is not overtaken is merely written back to its own slot. That costs more
/// than predictable branches, so each pass picks its kind from the previous one: a branchy
/// pass that turns out to carry often gives way to a branchless one from where it stands,
/// and a branchless pass that finds carries rare hands back to branchy ones. On random
/// `u64` input this is 1.8–2.6 times faster up to a few hundred elements and 1.2 times at
/// 1,000 (at 5,000, where the branches are better predicted, it is as fast as branching),
/// and on input whose elements are each a few slots from their places 1.5–2.6 times
/// faster; already sorted input is still done by one branchy pass.
///
/// The number of comparisons is exactly that of classic cocktail shaker sort with early exit
/// and last-swap bounds at both ends, and so is every outcome. Zero-sized elements, which are
/// all alike, are left as they are without comparing them.
///
/// # Properties
///
/// * **Stable**: equal elements keep their relative order (only strictly smaller elements are
/// overtaken going right, and only strictly greater ones going left).
/// * **In place**: `O(1)` auxiliary memory, no allocation.
/// * **Adaptive**: the cost grows with how far elements are from their sorted positions, in
/// either direction.
///
/// Let `I` be the number of inversions and `C` the number of carries (elements picked up and
/// moved at least one slot, counted once per pass). Each overtaken element moves one slot and
/// removes one inversion, so every inversion costs exactly one move, and each carry costs one
/// more for the final write.
///
/// | Case | Comparisons | Moves |
/// |---------------------------|-----------------|-----------------------|
/// | Best (already sorted) | `n - 1` | `0` |
/// | Any input | `≤ n(n - 1)/2` | `I + C ≤ 2I` |
/// | Average | `O(n²)` | `O(n²)` |
/// | Worst (reverse sorted) | `n(n - 1)/2` | `n(n + 1)/2 - 1` |
///
/// Cocktail shaker sort is quadratic and is mainly of educational value; prefer
/// [`slice::sort`] 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.
///
/// # Examples
///
/// ```
/// use a::sort::cocktail_shaker;
///
/// let mut v = [5, 1, 4, 2, 8, 0];
/// cocktail_shaker(&mut v);
/// assert_eq!(v, [0, 1, 2, 4, 5, 8]);
///
/// // The 0 at the end reaches the front in one backward pass.
/// let mut v = [1, 2, 3, 4, 5, 0];
/// cocktail_shaker(&mut v);
/// assert_eq!(v, [0, 1, 2, 3, 4, 5]);
///
/// let mut words = vec!["pear", "apple", "fig"];
/// cocktail_shaker(&mut words);
/// assert_eq!(words, ["apple", "fig", "pear"]);
/// ```
/// A branchless pass runs at the latency of a comparison, about twice the cost of a predicted
/// branchy step, while a carry costs a branchy pass up to two mispredictions: branchless
/// passes win once there is a carry per `CARRY_COST` comparisons. Tuned on `u64` from 16 to
/// 1,000 elements.
const CARRY_COST: usize = 16;
/// Passes shorter than this are judged as if they were this long, so that one carry in a
/// short pass does not make the next one branchless.
const JUDGE_MIN: usize = 32;
/// Whether a pass making `carries` carries in `comparisons` comparisons is cheaper branchless.
/// What a complete branchy backward pass found.
/// One backward pass over `base[..n]`, `n >= 2`, carrying small elements to the left and
/// branching on each comparison.
///
/// With `GIVE_UP`, the pass stops at the end of a carry once it has scanned at least
/// [`GIVE_UP_AFTER`] elements and makes a carry per [`CARRY_COST`] comparisons. It then
/// returns `Err((i0, first))`: `base[i0]` is the running minimum, `base[i0 + 1..n]` holds what
/// the pass has finished with, and `first` is one past the final index of its last move so
/// far, so that a branchless pass can take over from `i0`.
///
/// # Safety
///
/// `base[..n]` must be valid for reads and writes and hold initialised elements.
unsafe
/// Carries `*p`, the smallest element seen in a backward pass, left past every strictly
/// greater element before it, shifting each of those right by one slot. Returns the carried
/// element's final slot: `base`, or just after the first element not greater than it.
///
/// # Safety
///
/// `base[..=p]` must be valid for reads and writes and hold initialised elements, `p > base`,
/// and `*p < *p.sub(1)`.
unsafe
/// Runs a forward pass over `base[..n]` that is under way — its running maximum at `j0`,
/// everything before `j0` finished, `last` the final index of its last move so far — to the
/// end without branching on comparisons. Returns the final index of the last move and the
/// number of elements overtaken from `j0` on.
///
/// # Safety
///
/// `base[..n]` must be valid for reads and writes and hold initialised elements, and
/// `j0 < n`.
unsafe
/// Runs a backward pass that is under way — its running minimum at `i0`, everything after
/// `i0` finished, `first` one past the final index of its last move so far — to the front
/// without branching on comparisons. Returns one past the final index of the last move and
/// the number of elements overtaken from `i0` on.
///
/// # Safety
///
/// `base[..=i0]` must be valid for reads and writes and hold initialised elements.
unsafe
/// The mirror image of [`step`]: writes the greater of the element at `x` and the held one
/// into the vacant slot `*hole` (the held one if they are equal), keeps the smaller held, and
/// makes `x` the vacant slot. Returns whether the element at `x` was greater, that is,
/// overtaken.
///
/// # Safety
///
/// As for [`step`].
unsafe