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
use select_unpredictable;
use ;
use ptr;
/// Sorts a slice in place using bubble sort.
///
/// Each pass walks the unsorted prefix from left to right, carrying the largest element
/// seen so far towards the end until it meets an element that is not smaller than it.
/// After a pass, everything from the position of the last move onwards is in its final
/// place, so the next pass stops there; a pass that moves nothing ends the sort.
///
/// Four refinements keep the algorithm as cheap as bubble sort can be:
///
/// * **Last-move tracking.** The next pass scans only up to the last element that moved,
/// so already-sorted input finishes after a single pass of `n - 1` comparisons and
/// partially sorted tails are never rescanned.
/// * **Hole shifting instead of swapping.** An element travelling `k` slots to the right is
/// read once, the `k` smaller elements are each shifted left by one, and the element is
/// written once into its final slot: `k + 1` moves instead of the `3k` moves of `k` swaps.
/// * **Branchless passes for small elements.** Whether a comparison starts or ends a carry is
/// hard to predict on most inputs, and each misprediction costs as much as a dozen
/// comparisons. For elements of at most 8 bytes with no drop glue (integers, `char`,
/// `bool`, references), a pass can instead hold the running maximum in a register and, at
/// every comparison, write the smaller of it and the next element into the slot behind,
/// with no branch on the outcome. The comparisons and their outcomes are the same; an
/// element that is not overtaken is merely written back to its own slot.
/// * **Two passes at once.** Each branchless step waits for the one before it, so a single
/// pass runs at the latency of a comparison. Pass `k + 1` only reads slots that pass `k`
/// has finished with, so it can trail pass `k` through the slice in the same loop: two
/// independent chains of comparisons, each made exactly as if the passes ran one after
/// the other; on random `u64` input up to 1.3 times the speed of one branchless pass.
///
/// Branchless passes cost more than predictable branches, so the sort picks the kind of each
/// pass from the previous one: a branchy pass that turns out to carry often gives way to
/// branchless ones from where it stands, and branchless passes that move few elements hand
/// back to branchy ones. Already sorted input is done by one branchy pass, as before.
/// On random `u64` and `u32` input this sorts 1.2–2.9 times faster than branching on every
/// comparison (most around a hundred elements), and input whose elements are each a few slots
/// from their places up to 3.3 times faster.
///
/// The number of comparisons is exactly that of classic bubble sort with early exit, and so
/// is every outcome; only the order in which two consecutive passes make them is interleaved.
/// 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).
/// * **In place**: `O(1)` auxiliary memory, no allocation.
/// * **Adaptive**: the cost grows with how far elements are from their sorted positions.
///
/// | Case | Comparisons | Moves |
/// |---------------------------|-------------|--------|
/// | Best (already sorted) | `O(n)` | `0` |
/// | Average | `O(n²)` | `O(n²)`|
/// | Worst (reverse sorted) | `O(n²)` | `O(n²)`|
///
/// Bubble 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::bubble;
///
/// let mut v = [5, 1, 4, 2, 8, 0];
/// bubble(&mut v);
/// assert_eq!(v, [0, 1, 2, 4, 5, 8]);
///
/// let mut words = vec!["pear", "apple", "fig"];
/// bubble(&mut words);
/// assert_eq!(words, ["apple", "fig", "pear"]);
/// ```
/// Whether passes over elements of type `T` may run without branching on comparisons.
///
/// Measured on the whole sort on random input: 1.2–2.9 times faster for `u32` and `u64`;
/// for `(u64, u64)`, `Box<str>` and `String` up to 2.3 times slower (each step waits for a
/// longer comparison), and for `Box<u64>` 1.5–2.6 times slower (each comparison first loads
/// what the held element points to). Owning pointers are kept out by their drop glue; plain
/// references cannot be told apart from integers, take the branchless path, and pay that
/// load in the same way.
pub const
/// A branchy pass gives way to branchless ones once
/// `BRANCH_MOVE_COST · moves + BRANCH_CARRY_COST · carries` reaches the comparisons made: a
/// carry costs up to two mispredictions, while a move inside a predicted carry costs about
/// as much as a branchless step. Tuned on `u64` and `u32` from 16 to 5,000 elements.
const BRANCH_MOVE_COST: usize = 2;
const BRANCH_CARRY_COST: usize = 8;
/// A branchy pass checks whether to give up only after this many elements, so that a single
/// early carry does not decide for a whole pass.
pub const GIVE_UP_AFTER: usize = 32;
/// Whether a branchy pass looks for its next carry in a loop of its own.
///
/// That loop compiles to one taken branch per element, while the scan and the carry in one
/// loop compiled to two for `u64` in the adaptive passes, which made a scan twice as slow;
/// elements of more than 32 bytes gain 1.1–1.8 times on nearly sorted input. Elements of 9
/// to 32 bytes, and those with drop glue, keep the single loop: with it, random `String`s
/// sort up to 1.2 times faster than with the separate one.
pub const
/// What a complete branchy pass found.
pub
/// One forward pass over `base[..n]`, `n >= 2`, 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 `move_cost · moves + carry_cost · carries` has reached the
/// number of elements scanned, that is, once branches look expensive. It
/// then returns `Err((j0, last))`: `base[j0]` is the running maximum, `base[..j0]` holds what
/// the pass has finished with, and `last` is the final index of its last move so far, so that
/// a branchless pass can take over from `j0`.
///
/// # Safety
///
/// `base[..n]` must be valid for reads and writes and hold initialised elements.
pub unsafe
/// Carries `*p.sub(1)`, the largest element seen in a pass, right past every strictly
/// smaller element from `p` on, shifting each of those left by one slot. Returns the position
/// after the carried element's final slot: `end`, or the first element not smaller than it.
///
/// # Safety
///
/// `base[..end]` (for some `base < p`) must be valid for reads and writes and hold
/// initialised elements, `p < end`, and `*p < *p.sub(1)`.
unsafe
/// What a pair of branchless passes found about the second (trailing) one.
/// Runs the pass that is under way over `base[..lim]` — its running maximum at `j0`,
/// everything before `j0` finished, `last_l` the final index of its last move so far — to the
/// end, and the next pass over `base[..last of the first]` trailing it, both branchless.
///
/// The trailing pass reads `base[k]` only once `k` is below the leading pass's last move so
/// far, which is never more than the slot the leading pass holds vacant: it only sees slots
/// the leading pass has finished with, and it would scan them anyway, since the leading pass's
/// last move can only grow. So it makes exactly the comparisons it would make after the
/// leading pass, with the same outcomes.
///
/// # Safety
///
/// `base[..lim]` must be valid for reads and writes and hold initialised elements, `lim >= 2`,
/// `j0 < lim`, and if `j0 > 0`, `last_l < j0`.
unsafe
/// One branchless step of a pass: compares the element at `x` with the held one, writes the
/// smaller into the vacant slot `*hole` (the held one if they are equal, which keeps the sort
/// stable), keeps the larger held, and makes `x` the vacant slot. Returns whether the element
/// at `x` was smaller, that is, overtaken.
///
/// # Safety
///
/// `held` must point to an initialised element that belongs in the vacant slot `*hole`, and
/// `x` to an initialised element of the slice other than `*hole`; afterwards the held element
/// belongs in `x`. The comparison is the only call that can panic, and it runs before
/// anything is moved.
pub unsafe
/// An element temporarily moved out of a slice, plus the slot it will be written back to.
///
/// Writing back on drop is what keeps [`bubble`] panic-safe: the slice is whole again even
/// if a comparison unwinds while the element is out.
pub
/// A vacant slot of a slice, plus the element held outside the slice that belongs there.
///
/// Writing the held element back on drop is what keeps the branchless passes panic-safe.
pub