-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgravity_sort_benchmark.cpp
More file actions
3156 lines (2796 loc) · 130 KB
/
Copy pathgravity_sort_benchmark.cpp
File metadata and controls
3156 lines (2796 loc) · 130 KB
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <atomic>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <random>
#include <string>
#include <thread>
#include <vector>
using Clock = std::chrono::steady_clock;
using ms = std::chrono::duration<double, std::milli>;
struct Timer {
Clock::time_point start;
Timer() : start(Clock::now()) {}
double elapsed_ms() const {
return std::chrono::duration_cast<ms>(Clock::now() - start).count();
}
};
struct TrialStats {
double mean_ms = 0;
double median_ms = 0;
double min_ms = 0;
double max_ms = 0;
double stddev_ms = 0;
bool correct = true;
int reps = 0;
};
// ---------------------------------------------------------------------------
// Synthetic dataset generators
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> generate_random(std::size_t n,
std::uint32_t max_value = std::numeric_limits<std::uint32_t>::max())
{
std::mt19937_64 rng(123456789ULL + n);
std::uniform_int_distribution<std::uint32_t> dist(0, max_value);
std::vector<std::uint32_t> v;
v.reserve(n);
for (std::size_t i = 0; i < n; ++i) v.push_back(dist(rng));
return v;
}
static std::vector<std::uint32_t> generate_clustered(std::size_t n,
std::size_t centers = 32, std::uint32_t spread = 128)
{
std::mt19937_64 rng(987654321ULL + n);
std::uniform_int_distribution<std::uint32_t> center_dist(0,
std::numeric_limits<std::uint32_t>::max());
std::uniform_int_distribution<std::size_t> pick_center(0, centers - 1);
std::uniform_int_distribution<int> offset_dist(
-static_cast<int>(spread), static_cast<int>(spread));
std::vector<std::uint32_t> cv;
cv.reserve(centers);
for (std::size_t i = 0; i < centers; ++i) cv.push_back(center_dist(rng));
std::vector<std::uint32_t> v;
v.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
long long x = static_cast<long long>(cv[pick_center(rng)])
+ static_cast<long long>(offset_dist(rng));
if (x < 0) x = 0;
if (x > static_cast<long long>(std::numeric_limits<std::uint32_t>::max()))
x = std::numeric_limits<std::uint32_t>::max();
v.push_back(static_cast<std::uint32_t>(x));
}
return v;
}
static std::vector<std::uint32_t> generate_nearly_sorted(std::size_t n,
std::size_t swaps = 64)
{
std::mt19937_64 rng(4242424242ULL + n);
std::vector<std::uint32_t> v(n);
std::iota(v.begin(), v.end(), 0u);
if (n == 0) return v;
std::uniform_int_distribution<std::size_t> dist(0, n - 1);
for (std::size_t i = 0; i < std::min(swaps, n / 2); ++i) {
std::swap(v[dist(rng)], v[dist(rng)]);
}
return v;
}
static std::vector<std::uint32_t> generate_reverse_sorted(std::size_t n) {
std::vector<std::uint32_t> v(n);
for (std::size_t i = 0; i < n; ++i)
v[i] = static_cast<std::uint32_t>(n - 1 - i);
return v;
}
// Power-law: most values small, a few very large — common in real-world data
// (web traffic, file sizes, word frequencies, genomic hotspots)
static std::vector<std::uint32_t> generate_power_law(std::size_t n,
double exponent = 1.5)
{
std::mt19937_64 rng(1111111111ULL + n);
std::uniform_real_distribution<double> unit(0.0, 1.0);
std::vector<std::uint32_t> v;
v.reserve(n);
const double max32 = static_cast<double>(std::numeric_limits<std::uint32_t>::max());
for (std::size_t i = 0; i < n; ++i) {
// Inverse-CDF of a power-law: x = (1 - u)^(-1/(alpha-1))
double u = unit(rng);
double raw = std::pow(1.0 - u + 1e-12, -1.0 / (exponent - 1.0));
// Normalise into uint32 range; raw starts at 1 and grows without bound.
// We clip at a reasonable multiple so ~99% of values fit spread across range.
double clipped = std::min(raw / 1000.0, 1.0) * max32;
v.push_back(static_cast<std::uint32_t>(clipped));
}
return v;
}
// Pipe-organ: 0,1,2,...,n/2-1,n/2-1,...,1,0 — stress-tests adaptive sorts
static std::vector<std::uint32_t> generate_pipe_organ(std::size_t n) {
std::vector<std::uint32_t> v(n);
std::size_t half = n / 2;
for (std::size_t i = 0; i < half; ++i)
v[i] = static_cast<std::uint32_t>(i);
for (std::size_t i = half; i < n; ++i)
v[i] = static_cast<std::uint32_t>(n - 1 - i);
return v;
}
// All-equal: worst-case for algorithms that don't short-circuit on equal keys
static std::vector<std::uint32_t> generate_all_equal(std::size_t n) {
return std::vector<std::uint32_t>(n, 42u);
}
// Already sorted: best-case for adaptive sorts, measures overhead baseline
static std::vector<std::uint32_t> generate_already_sorted(std::size_t n) {
std::vector<std::uint32_t> v(n);
std::iota(v.begin(), v.end(), 0u);
return v;
}
// Bimodal: two well-separated clusters with a clean gap between them
// Perfect stress-test for Shock Wave Sort / Immiscible Fluids
static std::vector<std::uint32_t> generate_bimodal(std::size_t n) {
std::mt19937_64 rng(7777777777ULL + n);
std::uniform_int_distribution<std::uint32_t> lo(0, 100000);
std::uniform_int_distribution<std::uint32_t> hi(3000000, 3100000);
std::vector<std::uint32_t> v;
v.reserve(n);
for (std::size_t i = 0; i < n; ++i)
v.push_back((i % 2 == 0) ? lo(rng) : hi(rng));
// Shuffle to prevent order-based shortcuts
std::shuffle(v.begin(), v.end(), rng);
return v;
}
// Small range: all values in [0, 65535] — stresses algorithms that should detect
// the effective bit-width of the data (Isotope Separation Sort target)
static std::vector<std::uint32_t> generate_small_range(std::size_t n) {
std::mt19937_64 rng(3333333333ULL + n);
std::uniform_int_distribution<std::uint32_t> dist(0, 65535);
std::vector<std::uint32_t> v;
v.reserve(n);
for (std::size_t i = 0; i < n; ++i) v.push_back(dist(rng));
return v;
}
// Many sorted runs: K contiguous sorted segments concatenated — nearly-sorted
// variant that has more structure than random swaps; good for Phase Transition
static std::vector<std::uint32_t> generate_many_runs(std::size_t n,
std::size_t num_runs = 128)
{
std::mt19937_64 rng(5555555555ULL + n);
std::uniform_int_distribution<std::uint32_t> dist(0,
std::numeric_limits<std::uint32_t>::max());
std::vector<std::uint32_t> v;
v.reserve(n);
std::size_t run_len = std::max<std::size_t>(1, n / num_runs);
for (std::size_t r = 0; r < num_runs; ++r) {
std::size_t start = v.size();
std::size_t end = std::min(start + run_len, n);
while (v.size() < end) v.push_back(dist(rng));
std::sort(v.begin() + static_cast<std::ptrdiff_t>(start), v.end());
}
while (v.size() < n) v.push_back(dist(rng));
return v;
}
// High duplicates: only K distinct values across all n elements
// Pushes sorting to do mostly equality comparisons
static std::vector<std::uint32_t> generate_high_duplicates(std::size_t n,
std::size_t distinct = 16)
{
std::mt19937_64 rng(9999999999ULL + n);
std::uniform_int_distribution<std::size_t> pick(0, distinct - 1);
// Fixed distinct values spread across uint32 range
std::vector<std::uint32_t> keys(distinct);
for (std::size_t i = 0; i < distinct; ++i)
keys[i] = static_cast<std::uint32_t>((static_cast<std::uint64_t>(i) *
std::numeric_limits<std::uint32_t>::max()) / (distinct - 1));
std::vector<std::uint32_t> v;
v.reserve(n);
for (std::size_t i = 0; i < n; ++i) v.push_back(keys[pick(rng)]);
return v;
}
// ---------------------------------------------------------------------------
// Real-file dataset loaders
// Reads raw bytes from a file and reinterprets every 4-byte block as a
// uint32 (little-endian host order). This is fast and format-agnostic:
// DNA, XML, source code — everything becomes an integer sort workload.
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> load_file_as_uint32(
const std::string& path, std::size_t max_elements = 0)
{
std::ifstream f(path, std::ios::binary | std::ios::ate);
if (!f) return {};
std::streamsize bytes = f.tellg();
if (bytes <= 0) return {};
f.seekg(0);
std::size_t n_elems = static_cast<std::size_t>(bytes) / sizeof(std::uint32_t);
if (max_elements > 0 && n_elems > max_elements) n_elems = max_elements;
std::vector<std::uint32_t> v(n_elems);
f.read(reinterpret_cast<char*>(v.data()), n_elems * sizeof(std::uint32_t));
return v;
}
// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------
static void insertion_sort(std::vector<std::uint32_t>& a) {
for (std::size_t i = 1; i < a.size(); ++i) {
std::uint32_t x = a[i];
std::size_t j = i;
while (j > 0 && a[j - 1] > x) { a[j] = a[j - 1]; --j; }
a[j] = x;
}
}
// Sort each bucket in parallel using a work-stealing counter.
static void parallel_sort_buckets(std::vector<std::vector<std::uint32_t>>& buckets,
unsigned threads)
{
std::atomic<std::size_t> next{0};
std::vector<std::thread> pool;
pool.reserve(threads);
auto worker = [&]() {
for (;;) {
std::size_t b = next.fetch_add(1, std::memory_order_relaxed);
if (b >= buckets.size()) break;
auto& bkt = buckets[b];
if (bkt.size() <= 32) insertion_sort(bkt);
else std::sort(bkt.begin(), bkt.end());
}
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker);
for (auto& th : pool) th.join();
}
// ---------------------------------------------------------------------------
// Algorithm 1 (existing): Adaptive gravity bucket sort
// - Samples the data to build quantile-based splitters
// - O(log B) per element (binary search into splitter table)
// - Good when the distribution is truly unknown and non-monotone
// ---------------------------------------------------------------------------
static std::uint32_t percentile_from_sample(std::vector<std::uint32_t>& s, double p) {
if (s.empty()) return 0;
std::sort(s.begin(), s.end());
std::size_t i = static_cast<std::size_t>(p * (s.size() - 1));
return s[std::min(i, s.size() - 1)];
}
static std::vector<std::uint32_t> choose_splitters(
const std::vector<std::uint32_t>& arr, std::size_t B)
{
if (arr.empty() || B <= 1) return {};
std::size_t ss = std::min<std::size_t>(arr.size(), std::max<std::size_t>(1024, B * 32));
std::vector<std::uint32_t> sample;
sample.reserve(ss);
if (ss == arr.size()) {
sample = arr;
} else {
std::mt19937_64 rng(7777777ULL + arr.size());
std::uniform_int_distribution<std::size_t> dist(0, arr.size() - 1);
for (std::size_t i = 0; i < ss; ++i) sample.push_back(arr[dist(rng)]);
}
std::sort(sample.begin(), sample.end());
std::vector<std::uint32_t> sp;
sp.reserve(B - 1);
for (std::size_t i = 1; i < B; ++i) {
std::size_t idx = (i * sample.size()) / B;
sp.push_back(sample[std::min(idx, sample.size() - 1)]);
}
sp.erase(std::unique(sp.begin(), sp.end()), sp.end());
return sp;
}
static std::vector<std::uint32_t> gravity_bucket_sort_parallel(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (arr.size() <= 1) return arr;
std::uint32_t minv = *std::min_element(arr.begin(), arr.end());
std::uint32_t maxv = *std::max_element(arr.begin(), arr.end());
if (minv == maxv) return arr;
double range = static_cast<double>(maxv) - static_cast<double>(minv);
double iqr_ratio = 0.0;
{
std::size_t ss = std::min<std::size_t>(arr.size(), 4096);
std::vector<std::uint32_t> s;
s.reserve(ss);
if (ss == arr.size()) { s = arr; }
else {
std::mt19937_64 rng(1357911ULL + arr.size());
std::uniform_int_distribution<std::size_t> d(0, arr.size() - 1);
for (std::size_t i = 0; i < ss; ++i) s.push_back(arr[d(rng)]);
}
std::uint32_t q1 = percentile_from_sample(s, 0.25);
std::uint32_t q3 = percentile_from_sample(s, 0.75);
iqr_ratio = (range > 0) ? ((double)(q3 - q1) / (range + 1.0)) : 0.0;
}
std::size_t B = static_cast<std::size_t>(std::sqrt((double)arr.size()) * 1.25);
B = std::max<std::size_t>(32, std::min<std::size_t>(4096, B));
if (iqr_ratio < 0.05) B = std::max<std::size_t>(32, B / 2);
else if (iqr_ratio > 0.30) B = std::min<std::size_t>(4096, B * 2);
B = std::min<std::size_t>(B, std::max<std::size_t>(32, arr.size() / 8));
auto splitters = choose_splitters(arr, B);
if (splitters.empty()) return arr;
std::size_t bucket_total = splitters.size() + 1;
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads,
static_cast<unsigned>(arr.size())));
std::vector<std::vector<std::vector<std::uint32_t>>> local(
threads, std::vector<std::vector<std::uint32_t>>(bucket_total));
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto worker = [&](unsigned tid) {
std::size_t begin = (arr.size() * tid) / threads;
std::size_t end = (arr.size() * (tid + 1)) / threads;
for (std::size_t i = begin; i < end; ++i) {
std::uint32_t x = arr[i];
auto it = std::upper_bound(splitters.begin(), splitters.end(), x);
local[tid][static_cast<std::size_t>(it - splitters.begin())].push_back(x);
}
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker, t);
for (auto& th : pool) th.join();
}
std::vector<std::vector<std::uint32_t>> buckets(bucket_total);
for (std::size_t b = 0; b < bucket_total; ++b) {
std::size_t total = 0;
for (unsigned t = 0; t < threads; ++t) total += local[t][b].size();
buckets[b].reserve(total);
for (unsigned t = 0; t < threads; ++t) {
auto& src = local[t][b];
buckets[b].insert(buckets[b].end(), src.begin(), src.end());
}
}
parallel_sort_buckets(buckets, threads);
std::vector<std::uint32_t> out;
out.reserve(arr.size());
for (auto& bkt : buckets) out.insert(out.end(), bkt.begin(), bkt.end());
return out;
}
// ---------------------------------------------------------------------------
// Algorithm 2 (NEW): Gravity physics sort — fall-time log bucket mapping
//
// Physical model realised in code:
// A particle of value x falls at speed proportional to x (heavier = faster,
// like terminal velocity in a fluid). Its landing time is H/x, which is
// inversely proportional to x. Equal time intervals between bucket
// boundaries therefore correspond to *logarithmically spaced* value
// boundaries, because:
//
// t = H / x → x = H / t → log(x) is linear in log(t)
//
// Practical payoff:
// • O(1) bucket assignment per element — one log + multiply, no binary search.
// • No sampling pass needed — only min and max are required.
// • Naturally handles power-law / right-skewed data (common in real files):
// linear buckets pile everything into the first few; log buckets spread it
// evenly so each bucket's local sort is O((n/B) log(n/B)) not O(n log n).
// • Falls back to linear spacing when range is small (avoids log(0) edge case).
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> gravity_physics_sort(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (arr.size() <= 1) return arr;
// Single parallel pass: find min and max.
std::uint32_t minv = *std::min_element(arr.begin(), arr.end());
std::uint32_t maxv = *std::max_element(arr.begin(), arr.end());
if (minv == maxv) return arr;
std::size_t B = static_cast<std::size_t>(std::sqrt((double)arr.size()) * 2.0);
B = std::max<std::size_t>(32, std::min<std::size_t>(4096, B));
B = std::min<std::size_t>(B, std::max<std::size_t>(32, arr.size() / 4));
// Precompute the log-space scale factor.
// bucket(x) = floor( log1p(x - min) / log1p(max - min) * B )
// log1p avoids log(0) when x == min (gives bucket 0) or when range is 1.
const double log_range = std::log1p(static_cast<double>(maxv - minv));
const double inv_log_range = (log_range > 0.0) ? (1.0 / log_range) : 1.0;
const double scale = inv_log_range * static_cast<double>(B);
auto bucket_of = [&](std::uint32_t x) -> std::size_t {
if (x <= minv) return 0;
double pos = std::log1p(static_cast<double>(x - minv)) * scale;
std::size_t b = static_cast<std::size_t>(pos);
return b < B ? b : B - 1;
};
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads,
static_cast<unsigned>(arr.size())));
// Each thread scatters its slice into thread-local buckets to avoid locking.
std::vector<std::vector<std::vector<std::uint32_t>>> local(
threads, std::vector<std::vector<std::uint32_t>>(B));
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto worker = [&](unsigned tid) {
std::size_t begin = (arr.size() * tid) / threads;
std::size_t end = (arr.size() * (tid + 1)) / threads;
for (std::size_t i = begin; i < end; ++i)
local[tid][bucket_of(arr[i])].push_back(arr[i]);
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker, t);
for (auto& th : pool) th.join();
}
// Merge thread-local buckets.
std::vector<std::vector<std::uint32_t>> buckets(B);
for (std::size_t b = 0; b < B; ++b) {
std::size_t total = 0;
for (unsigned t = 0; t < threads; ++t) total += local[t][b].size();
buckets[b].reserve(total);
for (unsigned t = 0; t < threads; ++t) {
auto& src = local[t][b];
buckets[b].insert(buckets[b].end(), src.begin(), src.end());
}
}
parallel_sort_buckets(buckets, threads);
std::vector<std::uint32_t> out;
out.reserve(arr.size());
for (auto& bkt : buckets) out.insert(out.end(), bkt.begin(), bkt.end());
return out;
}
// ---------------------------------------------------------------------------
// Algorithm 3 (existing): Parallel 16-bit radix sort
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> parallel_radix_sort_16(
const std::vector<std::uint32_t>& input,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (input.size() <= 1) return input;
std::vector<std::uint32_t> a = input;
std::vector<std::uint32_t> out(a.size());
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads,
static_cast<unsigned>(a.size())));
const std::uint32_t base = 1u << 16;
const std::uint32_t mask = base - 1u;
std::uint32_t maxv = *std::max_element(a.begin(), a.end());
std::size_t passes = 0;
for (std::uint32_t x = maxv; x > 0; x >>= 16) ++passes;
if (passes == 0) passes = 1;
std::vector<std::vector<std::uint32_t>> local_counts(threads,
std::vector<std::uint32_t>(base, 0));
std::vector<std::vector<std::uint32_t>> thread_starts(threads,
std::vector<std::uint32_t>(base, 0));
std::vector<std::uint32_t> global_counts(base, 0);
for (std::size_t pass = 0; pass < passes; ++pass) {
std::size_t shift = pass * 16;
std::fill(global_counts.begin(), global_counts.end(), 0);
for (unsigned t = 0; t < threads; ++t)
std::fill(local_counts[t].begin(), local_counts[t].end(), 0);
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto count_worker = [&](unsigned tid) {
std::size_t begin = (a.size() * tid) / threads;
std::size_t end = (a.size() * (tid + 1)) / threads;
auto& lc = local_counts[tid];
for (std::size_t i = begin; i < end; ++i)
++lc[(a[i] >> shift) & mask];
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(count_worker, t);
for (auto& th : pool) th.join();
}
for (std::uint32_t d = 0; d < base; ++d) {
std::uint32_t sum = 0;
for (unsigned t = 0; t < threads; ++t) sum += local_counts[t][d];
global_counts[d] = sum;
}
std::uint32_t total = 0;
std::vector<std::uint32_t> prefix(base, 0);
for (std::uint32_t d = 0; d < base; ++d) { prefix[d] = total; total += global_counts[d]; }
for (std::uint32_t d = 0; d < base; ++d) {
std::uint32_t running = prefix[d];
for (unsigned t = 0; t < threads; ++t) {
thread_starts[t][d] = running;
running += local_counts[t][d];
}
}
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto scatter_worker = [&](unsigned tid) {
std::size_t begin = (a.size() * tid) / threads;
std::size_t end = (a.size() * (tid + 1)) / threads;
auto starts = thread_starts[tid];
for (std::size_t i = begin; i < end; ++i) {
std::uint32_t x = a[i];
std::uint32_t d = (x >> shift) & mask;
out[starts[d]++] = x;
}
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(scatter_worker, t);
for (auto& th : pool) th.join();
}
a.swap(out);
}
return a;
}
// ---------------------------------------------------------------------------
// Dead-Weight Sort (Prefix Compression Radix)
// Physics: leading zero bits are drag that doesn't affect ordering but wastes
// radix passes. Sort by (x - min) using digit_bits = ceil(effective_bits/2),
// so count arrays fit in L1 when the value range is small.
//
// For range <= 2^16: 1 pass of 16 bits (same as parallel_radix)
// For range in (2^16, 2^20]: 2 passes of 10 bits (1024-entry count, L1-friendly)
// For range in (2^20, 2^24]: 2 passes of 12 bits (4096-entry count, L1-friendly)
// For range in (2^24, 2^32]: 2 passes of 16 bits (same as parallel_radix)
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> dead_weight_sort(
const std::vector<std::uint32_t>& input,
unsigned threads_hint = std::thread::hardware_concurrency())
{
const std::size_t n = input.size();
if (n <= 1) return input;
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads, static_cast<unsigned>(n)));
std::uint32_t minv = input[0], maxv = input[0];
for (auto x : input) {
if (x < minv) minv = x;
if (x > maxv) maxv = x;
}
const std::uint32_t range = maxv - minv;
if (range == 0) return input; // all equal — already sorted
// Compute effective bit-width: bits in range
int effective_bits = 1;
if (range > 0) effective_bits = 32 - __builtin_clz(range);
// Choose digit width: smallest that covers effective_bits in at most 2 passes
int digit_bits;
int passes;
if (effective_bits <= 16) {
digit_bits = 16; passes = 1;
} else if (effective_bits <= 20) {
digit_bits = 10; passes = 2;
} else if (effective_bits <= 24) {
digit_bits = 12; passes = 2;
} else {
digit_bits = 16; passes = 2;
}
const std::uint32_t base = 1u << digit_bits;
const std::uint32_t mask = base - 1u;
// Work on shifted values: sort (x - minv) so only effective_bits matter
std::vector<std::uint32_t> a(n), b(n);
for (std::size_t i = 0; i < n; ++i) a[i] = input[i] - minv;
std::vector<std::vector<std::uint32_t>> local_counts(threads,
std::vector<std::uint32_t>(base, 0));
std::vector<std::vector<std::uint32_t>> thread_starts(threads,
std::vector<std::uint32_t>(base, 0));
std::vector<std::uint32_t> global_counts(base, 0);
for (int pass = 0; pass < passes; ++pass) {
int shift = pass * digit_bits;
std::fill(global_counts.begin(), global_counts.end(), 0);
for (unsigned t = 0; t < threads; ++t)
std::fill(local_counts[t].begin(), local_counts[t].end(), 0);
{
std::vector<std::thread> pool; pool.reserve(threads);
auto count_worker = [&](unsigned tid) {
std::size_t beg = (n * tid) / threads, end = (n * (tid+1)) / threads;
auto& lc = local_counts[tid];
for (std::size_t i = beg; i < end; ++i) ++lc[(a[i] >> shift) & mask];
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(count_worker, t);
for (auto& th : pool) th.join();
}
for (std::uint32_t d = 0; d < base; ++d) {
std::uint32_t sum = 0;
for (unsigned t = 0; t < threads; ++t) sum += local_counts[t][d];
global_counts[d] = sum;
}
std::uint32_t total = 0;
std::vector<std::uint32_t> prefix(base, 0);
for (std::uint32_t d = 0; d < base; ++d) { prefix[d] = total; total += global_counts[d]; }
for (std::uint32_t d = 0; d < base; ++d) {
std::uint32_t running = prefix[d];
for (unsigned t = 0; t < threads; ++t) {
thread_starts[t][d] = running;
running += local_counts[t][d];
}
}
{
std::vector<std::thread> pool; pool.reserve(threads);
auto scatter_worker = [&](unsigned tid) {
std::size_t beg = (n * tid) / threads, end = (n * (tid+1)) / threads;
auto starts = thread_starts[tid];
for (std::size_t i = beg; i < end; ++i) {
std::uint32_t x = a[i];
std::uint32_t d = (x >> shift) & mask;
b[starts[d]++] = x;
}
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(scatter_worker, t);
for (auto& th : pool) th.join();
}
a.swap(b);
}
// Convert back to original values: add minv
for (std::size_t i = 0; i < n; ++i) a[i] += minv;
return a;
}
static std::vector<std::uint32_t> dead_weight_wrapper(
const std::vector<std::uint32_t>& in) { return dead_weight_sort(in); }
// ---------------------------------------------------------------------------
// Wrappers (function-pointer compatible)
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> std_sort_wrapper(
const std::vector<std::uint32_t>& input)
{
std::vector<std::uint32_t> a = input;
std::sort(a.begin(), a.end());
return a;
}
static std::vector<std::uint32_t> std_stable_sort_wrapper(
const std::vector<std::uint32_t>& input)
{
std::vector<std::uint32_t> a = input;
std::stable_sort(a.begin(), a.end());
return a;
}
// ---------------------------------------------------------------------------
// Flash Sort (Neubert 1998) — parallel version using LINEAR bucket spacing
// Formula: bucket = floor( (B-1) * (x - min) / (max - min) )
// Same parallel structure as gravity_physics_sort for fair comparison.
// The ONLY difference is linear vs log bucket assignment.
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> flash_sort_linear(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (arr.size() <= 1) return arr;
std::uint32_t minv = *std::min_element(arr.begin(), arr.end());
std::uint32_t maxv = *std::max_element(arr.begin(), arr.end());
if (minv == maxv) return arr;
std::size_t B = static_cast<std::size_t>(std::sqrt((double)arr.size()) * 2.0);
B = std::max<std::size_t>(32, std::min<std::size_t>(4096, B));
B = std::min<std::size_t>(B, std::max<std::size_t>(32, arr.size() / 4));
// Neubert's linear formula (parallel version)
const double range = static_cast<double>(maxv) - static_cast<double>(minv);
const double scale = static_cast<double>(B - 1) / range;
auto bucket_of = [&](std::uint32_t x) -> std::size_t {
if (x <= minv) return 0;
if (x >= maxv) return B - 1;
return static_cast<std::size_t>((static_cast<double>(x - minv)) * scale);
};
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads,
static_cast<unsigned>(arr.size())));
std::vector<std::vector<std::vector<std::uint32_t>>> local(
threads, std::vector<std::vector<std::uint32_t>>(B));
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto worker = [&](unsigned tid) {
std::size_t begin = (arr.size() * tid) / threads;
std::size_t end = (arr.size() * (tid + 1)) / threads;
for (std::size_t i = begin; i < end; ++i)
local[tid][bucket_of(arr[i])].push_back(arr[i]);
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker, t);
for (auto& th : pool) th.join();
}
std::vector<std::vector<std::uint32_t>> buckets(B);
for (std::size_t b = 0; b < B; ++b) {
std::size_t total = 0;
for (unsigned t = 0; t < threads; ++t) total += local[t][b].size();
buckets[b].reserve(total);
for (unsigned t = 0; t < threads; ++t) {
auto& src = local[t][b];
buckets[b].insert(buckets[b].end(), src.begin(), src.end());
}
}
parallel_sort_buckets(buckets, threads);
std::vector<std::uint32_t> out;
out.reserve(arr.size());
for (auto& bkt : buckets) out.insert(out.end(), bkt.begin(), bkt.end());
return out;
}
static std::vector<std::uint32_t> flash_sort_wrapper(
const std::vector<std::uint32_t>& input) { return flash_sort_linear(input); }
// ---------------------------------------------------------------------------
// Algorithm NEW: Adaptive Box-Cox Sort
//
// Physical story: GPS assumes particles fall through a power-law fluid (heavy
// drag, log spacing). Flash Sort assumes vacuum (linear spacing). Real data
// sits somewhere in between — the drag exponent equals the distribution shape.
//
// One extra statistic: compute mean alongside min/max (single pass, no
// sampling). The mean's position within [min,max] reveals the skew:
//
// lambda = 2 * (mean - min) / (max - min)
//
// lambda ~= 1 → mean is centred → uniform data → linear buckets (Flash Sort)
// lambda ~= 0 → mean hugs left → power-law data → log buckets (GPS)
// 0 < lambda < 1 → intermediate skew → Box-Cox buckets
//
// Bucket formula (Box-Cox with offset to avoid log(0)):
// bucket(x) = floor( ((x-min+1)^lambda - 1) / ((max-min+1)^lambda - 1) * B )
//
// This is the first no-sampling distribution sort that adapts its spacing
// exponent from a single-pass moment estimate (mean).
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> adaptive_box_cox_sort(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (arr.size() <= 1) return arr;
// Single pass: min, max, and mean together — O(n), no sampling.
std::uint32_t minv = arr[0], maxv = arr[0];
double sum = 0.0;
for (auto x : arr) {
if (x < minv) minv = x;
if (x > maxv) maxv = x;
sum += static_cast<double>(x);
}
if (minv == maxv) return arr;
double mean = sum / static_cast<double>(arr.size());
double range = static_cast<double>(maxv) - static_cast<double>(minv);
// Estimate lambda: normalised mean position tells us the distribution shape.
double lam = 2.0 * (mean - static_cast<double>(minv)) / range;
lam = std::max(0.02, std::min(1.98, lam)); // clamp away from singularities
std::size_t B = static_cast<std::size_t>(std::sqrt((double)arr.size()) * 2.0);
B = std::max<std::size_t>(32, std::min<std::size_t>(4096, B));
B = std::min<std::size_t>(B, std::max<std::size_t>(32, arr.size() / 4));
// Precompute scale factor based on chosen regime.
// Regime thresholds chosen to avoid numerical instability near 0 and 1.
const bool use_log = (lam < 0.10); // near GPS
const bool use_linear = (lam > 0.90); // near Flash Sort
const double log_range = std::log1p(range);
const double inv_log = (log_range > 0.0) ? (static_cast<double>(B) / log_range) : 1.0;
const double linear_scale = static_cast<double>(B - 1) / range;
// Box-Cox denominator: (range+1)^lambda - 1
const double denom_bc = std::pow(range + 1.0, lam) - 1.0;
const double inv_bc = (denom_bc > 1e-15) ? (static_cast<double>(B) / denom_bc) : 1.0;
auto bucket_of = [&](std::uint32_t x) -> std::size_t {
if (x <= minv) return 0;
if (x >= maxv) return B - 1;
double d = static_cast<double>(x - minv);
double pos;
if (use_log) {
pos = std::log1p(d) * inv_log;
} else if (use_linear) {
pos = d * linear_scale;
} else {
pos = (std::pow(d + 1.0, lam) - 1.0) * inv_bc;
}
std::size_t b = static_cast<std::size_t>(pos);
return b < B ? b : B - 1;
};
unsigned threads = threads_hint == 0 ? 4u : threads_hint;
threads = std::max(1u, std::min<unsigned>(threads,
static_cast<unsigned>(arr.size())));
std::vector<std::vector<std::vector<std::uint32_t>>> local(
threads, std::vector<std::vector<std::uint32_t>>(B));
{
std::vector<std::thread> pool;
pool.reserve(threads);
auto worker = [&](unsigned tid) {
std::size_t begin = (arr.size() * tid) / threads;
std::size_t end = (arr.size() * (tid + 1)) / threads;
for (std::size_t i = begin; i < end; ++i)
local[tid][bucket_of(arr[i])].push_back(arr[i]);
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker, t);
for (auto& th : pool) th.join();
}
std::vector<std::vector<std::uint32_t>> buckets(B);
for (std::size_t b = 0; b < B; ++b) {
std::size_t total = 0;
for (unsigned t = 0; t < threads; ++t) total += local[t][b].size();
buckets[b].reserve(total);
for (unsigned t = 0; t < threads; ++t) {
auto& src = local[t][b];
buckets[b].insert(buckets[b].end(), src.begin(), src.end());
}
}
parallel_sort_buckets(buckets, threads);
std::vector<std::uint32_t> out;
out.reserve(arr.size());
for (auto& bkt : buckets) out.insert(out.end(), bkt.begin(), bkt.end());
return out;
}
static std::vector<std::uint32_t> adaptive_box_cox_wrapper(
const std::vector<std::uint32_t>& input) { return adaptive_box_cox_sort(input); }
// ---------------------------------------------------------------------------
// Idea 1: Variance-Adaptive Tank Depth
// Physics: tank depth needed = f(spread of particle sizes). Low σ → shallow
// tank (few buckets). High σ → deep tank (many buckets).
// Adds sum_sq to the single pass → σ → scale B by sigma_norm.
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> variance_adaptive_sort(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())
{
if (arr.size() <= 1) return arr;
std::uint32_t minv = arr[0], maxv = arr[0];
double sum = 0.0, sum_sq = 0.0;
for (auto x : arr) {
if (x < minv) minv = x;
if (x > maxv) maxv = x;
double xd = static_cast<double>(x);
sum += xd;
sum_sq += xd * xd;
}
if (minv == maxv) return arr;
const double nd = static_cast<double>(arr.size());
double mean = sum / nd;
double range = static_cast<double>(maxv) - static_cast<double>(minv);
double variance = std::max(0.0, sum_sq / nd - mean * mean);
double sigma_norm = (range > 0.0) ? std::min(1.0, std::sqrt(variance) / (range / 2.0)) : 1.0;
double lam = 2.0 * (mean - static_cast<double>(minv)) / range;
lam = std::max(0.02, std::min(1.98, lam));
// Variance-scaled tank depth: low spread → fewer buckets, high spread → more
double b_scale = std::max(0.4, std::min(2.0, sigma_norm * 1.5 + 0.3));
std::size_t B = static_cast<std::size_t>(std::sqrt((double)arr.size()) * 2.0 * b_scale);
B = std::max<std::size_t>(32, std::min<std::size_t>(4096, B));
B = std::min<std::size_t>(B, std::max<std::size_t>(32, arr.size() / 4));
const bool use_log = (lam < 0.10);
const bool use_linear = (lam > 0.90);
const double log_range = std::log1p(range);
const double inv_log = (log_range > 0.0) ? (static_cast<double>(B) / log_range) : 1.0;
const double linear_scale = static_cast<double>(B - 1) / range;
const double denom_bc = std::pow(range + 1.0, lam) - 1.0;
const double inv_bc = (denom_bc > 1e-15) ? (static_cast<double>(B) / denom_bc) : 1.0;
auto bucket_of = [&](std::uint32_t x) -> std::size_t {
if (x <= minv) return 0;
if (x >= maxv) return B - 1;
double d = static_cast<double>(x - minv);
double pos = use_log ? std::log1p(d) * inv_log
: use_linear ? d * linear_scale
: (std::pow(d + 1.0, lam) - 1.0) * inv_bc;
std::size_t b = static_cast<std::size_t>(pos);
return b < B ? b : B - 1;
};
unsigned threads = std::max(1u, std::min<unsigned>(
threads_hint == 0 ? 4u : threads_hint, static_cast<unsigned>(arr.size())));
std::vector<std::vector<std::vector<std::uint32_t>>> local(
threads, std::vector<std::vector<std::uint32_t>>(B));
{
std::vector<std::thread> pool; pool.reserve(threads);
auto worker = [&](unsigned tid) {
std::size_t begin = (arr.size() * tid) / threads;
std::size_t end = (arr.size() * (tid + 1)) / threads;
for (std::size_t i = begin; i < end; ++i)
local[tid][bucket_of(arr[i])].push_back(arr[i]);
};
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker, t);
for (auto& th : pool) th.join();
}
std::vector<std::vector<std::uint32_t>> buckets(B);
for (std::size_t b = 0; b < B; ++b) {
std::size_t total = 0;
for (unsigned t = 0; t < threads; ++t) total += local[t][b].size();
buckets[b].reserve(total);
for (unsigned t = 0; t < threads; ++t) {
auto& src = local[t][b];
buckets[b].insert(buckets[b].end(), src.begin(), src.end());
}
}
parallel_sort_buckets(buckets, threads);
std::vector<std::uint32_t> out; out.reserve(arr.size());
for (auto& bkt : buckets) out.insert(out.end(), bkt.begin(), bkt.end());
return out;
}
static std::vector<std::uint32_t> variance_adaptive_wrapper(
const std::vector<std::uint32_t>& in) { return variance_adaptive_sort(in); }
// ---------------------------------------------------------------------------
// Idea 2: Pressure Redistribution (Two-Pass Equalization)
// Physics: overpressured tank regions push particles sideways into adjacent
// zones. After the first GPS scatter, if any bucket holds >2*(n/B) elements,
// recompute value boundaries from cumulative occupancy and re-scatter.
// Zero overhead on well-behaved data.
// ---------------------------------------------------------------------------
static std::vector<std::uint32_t> pressure_equalized_sort(
const std::vector<std::uint32_t>& arr,
unsigned threads_hint = std::thread::hardware_concurrency())