-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrailsort.hpp
1356 lines (1165 loc) · 46.2 KB
/
grailsort.hpp
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
// MayanSort - many sort algorithms implementation in C++ 20.
//
// MIT License:
// Copyright (c) 2023 The pysoft group.
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this softwareand associated documentation files(the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and /or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions :
//
// The above copyright noticeand this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Copied from https://github.com/HolyGrailSortProject/Rewritten-Grailsort/blob/master/C%2B%2B/Morwenn's%20rewrite%20of%20Summer%20Dragonfly's%20GrailSort/grailsort.h
// Original File Header:
/*
* MIT License
*
* Copyright (c) 2013 Andrey Astrelin
* Copyright (c) 2020-2021 The Holy Grail Sort Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* The Holy Grail Sort Project
* Project Manager: Summer Dragonfly
* Project Contributors: 666666t
* Anonymous0726
* aphitorite
* Control
* dani_dlg
* DeveloperSort
* EilrahcF
* Enver
* Gaming32
* lovebuny
* Morwenn
* MP
* phoenixbound
* Spex_guy
* thatsOven
* _fluffyy
*
* Special thanks to "The Studio" Discord community!
*/
#ifndef REWRITTEN_GRAILSORT_H_
#define REWRITTEN_GRAILSORT_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <algorithm>
#include <functional>
#include <iterator>
#include <type_traits>
#include <utility>
namespace MayanSort {
namespace grailsort_detail
{
// Credit to phoenixbound for this clever idea
enum struct Subarray
{
LEFT,
RIGHT
};
template<typename Compare>
struct ThreeWayCompare
{
Compare compare;
explicit ThreeWayCompare(Compare&& comp) :
compare(std::forward<Compare>(comp))
{}
template<typename T, typename U>
int operator()(T&& lhs, U&& rhs)
{
if (compare(lhs, rhs)) {
return -1;
}
if (compare(rhs, lhs)) {
return 1;
}
return 0;
}
};
struct GrailSort
{
int currBlockLen;
Subarray currBlockOrigin;
template<typename RandomAccessIterator>
static void BlockSwap(RandomAccessIterator array, int a, int b, int blockLen) {
std::swap_ranges(array + a, array + (a + blockLen), array + b);
}
// Swaps the order of two adjacent blocks whose lengths may or may not be equal.
// Variant of the Gries-Mills algorithm, which is basically recursive block swaps
template<typename RandomAccessIterator>
static void Rotate(RandomAccessIterator array, int start, int leftLen, int rightLen) {
while (leftLen > 0 && rightLen > 0) {
if (leftLen <= rightLen) {
BlockSwap(array, start, start + leftLen, leftLen);
start += leftLen;
rightLen -= leftLen;
}
else {
BlockSwap(array, start + leftLen - rightLen, start + leftLen, rightLen);
leftLen -= rightLen;
}
}
}
// Variant of Insertion Sort that utilizes swaps instead of overwrites.
// Also known as "Optimized Gnomesort".
template<typename RandomAccessIterator, typename Compare>
static void InsertSort(RandomAccessIterator array, int start, int length, Compare comp) {
for (int item = 1; item < length; item++) {
int left = start + item - 1;
int right = start + item;
while (left >= start && comp(array[left], array[right]) > 0) {
std::iter_swap(array + left, array + right);
left--;
right--;
}
}
}
template<typename RandomAccessIterator, typename Compare, typename T>
static int BinarySearchLeft(RandomAccessIterator array, int start, int length, const T& target, Compare comp) {
int left = 0;
int right = length;
while (left < right) {
// equivalent to (left + right) / 2 with added overflow protection
int middle = left + ((right - left) / 2);
if (comp(array[start + middle], target) < 0) {
left = middle + 1;
}
else {
right = middle;
}
}
return left;
}
// Credit to Anonymous0726 for debugging
template<typename RandomAccessIterator, typename Compare, typename T>
static int BinarySearchRight(RandomAccessIterator array, int start, int length, const T& target, Compare comp) {
int left = 0;
int right = length;
while (left < right) {
// equivalent to (left + right) / 2 with added overflow protection
int middle = left + ((right - left) / 2);
if (comp(array[start + middle], target) > 0) {
right = middle;
}
else {
left = middle + 1;
}
}
// OFF-BY-ONE BUG FIXED: used to be `return right - 1;`
return right;
}
// cost: 2 * length + idealKeys^2 / 2
template<typename RandomAccessIterator, typename Compare>
static int CollectKeys(RandomAccessIterator array, int start, int length, int idealKeys, Compare comp) {
int keysFound = 1; // by itself, the first item in the array is our first unique key
int firstKey = 0; // the first item in the array is at the first position in the array
int currKey = 1; // the index used for finding potentially unique items ("keys") in the array
while (currKey < length && keysFound < idealKeys) {
// Find the location in the key-buffer where our current key can be inserted in sorted order.
// If the key at insertPos is equal to currKey, then currKey isn't unique and we move on.
int insertPos = BinarySearchLeft(array, start + firstKey, keysFound, array[start + currKey], comp);
// The second part of this conditional does the equal check we were just talking about; however,
// if currKey is larger than everything in the key-buffer (meaning insertPos == keysFound),
// then that also tells us it wasn't *equal* to anything in the key-buffer. Magic! :)
if (insertPos == keysFound || comp(array[start + currKey], array[start + firstKey + insertPos]) != 0) {
// First, rotate the key-buffer over to currKey's immediate left...
// (this helps save a TON of swaps/writes!!!)
Rotate(array, start + firstKey, keysFound, currKey - (firstKey + keysFound));
// Update the new position of firstKey...
firstKey = currKey - keysFound;
// Then, "insertion sort" currKey to its spot in the key-buffer!
Rotate(array, start + firstKey + insertPos, keysFound - insertPos, 1);
// One step closer to idealKeys.
keysFound++;
}
// Move on and test the next key...
currKey++;
}
// Bring however many keys we found back to the beginning of our array,
// and return the number of keys collected.
Rotate(array, start, firstKey, keysFound);
return keysFound;
}
template<typename RandomAccessIterator, typename Compare>
static void PairwiseSwaps(RandomAccessIterator array, int start, int length, Compare comp) {
int index;
for (index = 1; index < length; index += 2) {
int left = start + index - 1;
int right = start + index;
if (comp(array[left], array[right]) > 0) {
std::swap(array[left - 2], array[right]);
std::swap(array[right - 2], array[left]);
}
else {
std::swap(array[left - 2], array[left]);
std::swap(array[right - 2], array[right]);
}
}
int left = start + index - 1;
if (left < start + length) {
std::swap(array[left - 2], array[left]);
}
}
template<typename RandomAccessIterator, typename Compare>
static void PairwiseWrites(RandomAccessIterator array, int start, int length, Compare comp) {
int index;
for (index = 1; index < length; index += 2) {
int left = start + index - 1;
int right = start + index;
if (comp(array[left], array[right]) > 0) {
array[left - 2] = std::move(array[right]);
array[right - 2] = std::move(array[left]);
}
else {
array[left - 2] = std::move(array[left]);
array[right - 2] = std::move(array[right]);
}
}
int left = start + index - 1;
if (left < start + length) {
array[left - 2] = std::move(array[left]);
}
}
// array[buffer .. start - 1] <=> "scrolling buffer"
//
// "scrolling buffer" + array[start, middle - 1] + array[middle, end - 1]
// --> array[buffer, buffer + end - 1] + "scrolling buffer"
template<typename RandomAccessIterator, typename Compare>
static void MergeForwards(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
auto buffer = array + (start - bufferOffset);
auto left = array + start;
auto middle = array + (start + leftLen);
auto right = middle;
auto end = middle + rightLen;
while (right != end) {
if (left == middle || comp(*left, *right) > 0) {
std::iter_swap(buffer, right);
++right;
}
else {
std::iter_swap(buffer, left);
++left;
}
++buffer;
}
if (buffer != left) {
std::swap_ranges(buffer, buffer + (middle - left), left);
}
}
// credit to 666666t for thorough bug-checking/fixing
template<typename RandomAccessIterator, typename Compare>
static void MergeBackwards(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
// used to be '= start'
int end = start - 1;
// used to be '= start + leftLen - 1'
int left = end + leftLen;
int middle = left;
// OFF-BY-ONE BUG FIXED: used to be `int right = middle + rightLen - 1;`
int right = middle + rightLen;
// OFF-BY-ONE BUG FIXED: used to be `int buffer = right + bufferOffset - 1;`
int buffer = right + bufferOffset;
// used to be 'left >= end'
while (left > end) {
if (right == middle || comp(array[left], array[right]) > 0) {
std::swap(array[buffer], array[left]);
left--;
}
else {
std::swap(array[buffer], array[right]);
right--;
}
buffer--;
}
if (right != buffer) {
while (right > middle) {
std::swap(array[buffer], array[right]);
buffer--;
right--;
}
}
}
// array[buffer .. start - 1] <=> "free space"
//
// "free space" + array[start, middle - 1] + array[middle, end - 1]
// --> array[buffer, buffer + end - 1] + "free space"
//
// FUNCTION RENAMED: More consistent with "out-of-place" being at the end
template<typename RandomAccessIterator, typename Compare>
static void MergeOutOfPlace(RandomAccessIterator array, int start, int leftLen, int rightLen, int bufferOffset, Compare comp) {
int buffer = start - bufferOffset;
int left = start;
int middle = start + leftLen;
int right = middle;
int end = middle + rightLen;
while (right < end) {
if (left == middle || comp(array[left], array[right]) > 0) {
array[buffer] = std::move(array[right]);
right++;
}
else {
array[buffer] = std::move(array[left]);
left++;
}
buffer++;
}
if (buffer != left) {
while (left < middle) {
array[buffer] = std::move(array[left]);
buffer++;
left++;
}
}
}
template<typename RandomAccessIterator, typename Compare>
static void BuildInPlace(RandomAccessIterator array, int start, int length, int currentLen, int bufferLen, Compare comp) {
for (int mergeLen = currentLen; mergeLen < bufferLen; mergeLen *= 2) {
int fullMerge = 2 * mergeLen;
int mergeIndex;
int mergeEnd = start + length - fullMerge;
int bufferOffset = mergeLen;
for (mergeIndex = start; mergeIndex <= mergeEnd; mergeIndex += fullMerge) {
MergeForwards(array, mergeIndex, mergeLen, mergeLen, bufferOffset, comp);
}
int leftOver = length - (mergeIndex - start);
if (leftOver > mergeLen) {
MergeForwards(array, mergeIndex, mergeLen, leftOver - mergeLen, bufferOffset, comp);
}
else {
Rotate(array, mergeIndex - mergeLen, mergeLen, leftOver);
}
start -= mergeLen;
}
int fullMerge = 2 * bufferLen;
int lastBlock = length % fullMerge;
int lastOffset = start + length - lastBlock;
if (lastBlock <= bufferLen) {
Rotate(array, lastOffset, lastBlock, bufferLen);
}
else {
MergeBackwards(array, lastOffset, bufferLen, lastBlock - bufferLen, bufferLen, comp);
}
for (int mergeIndex = lastOffset - fullMerge; mergeIndex >= start; mergeIndex -= fullMerge) {
MergeBackwards(array, mergeIndex, bufferLen, bufferLen, bufferLen, comp);
}
}
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void BuildOutOfPlace(RandomAccessIterator array, int start, int length, int bufferLen, int extLen,
BufferIterator extBuffer, Compare comp) {
std::move(array + (start - extLen), array + start, extBuffer);
PairwiseWrites(array, start, length, comp);
start -= 2;
int mergeLen;
for (mergeLen = 2; mergeLen < extLen; mergeLen *= 2) {
int fullMerge = 2 * mergeLen;
int mergeIndex;
int mergeEnd = start + length - fullMerge;
int bufferOffset = mergeLen;
for (mergeIndex = start; mergeIndex <= mergeEnd; mergeIndex += fullMerge) {
MergeOutOfPlace(array, mergeIndex, mergeLen, mergeLen, bufferOffset, comp);
}
int leftOver = length - (mergeIndex - start);
if (leftOver > mergeLen) {
MergeOutOfPlace(array, mergeIndex, mergeLen, leftOver - mergeLen, bufferOffset, comp);
}
else {
// MINOR CHANGE: Used to be a loop; much clearer now
std::move(array + mergeIndex, array + (mergeIndex + leftOver), array + (mergeIndex - mergeLen));
}
start -= mergeLen;
}
std::move(extBuffer, extBuffer + extLen, array + (start + length));
BuildInPlace(array, start, length, mergeLen, bufferLen, comp);
}
// build blocks of length 'bufferLen'
// input: [start - mergeLen, start - 1] elements are buffer
// output: first 'bufferLen' elements are buffer, blocks (2 * bufferLen) and last subblock sorted
template<typename RandomAccessIterator, typename BufferIterator, typename Compare>
void BuildBlocks(RandomAccessIterator array, int start, int length, int bufferLen,
BufferIterator extBuffer, int extBufferLen, Compare comp) {
if (extBufferLen != 0) {
int extLen;
if (bufferLen < extBufferLen) {
extLen = bufferLen;
}
else {
// max power of 2 -- just in case
extLen = 1;
while ((extLen * 2) <= extBufferLen) {
extLen *= 2;
}
}
BuildOutOfPlace(array, start, length, bufferLen, extLen, extBuffer, comp);
}
else {
PairwiseSwaps(array, start, length, comp);
BuildInPlace(array, start - 2, length, 2, bufferLen, comp);
}
}
// Returns the final position of 'medianKey'
template<typename RandomAccessIterator, typename Compare>
static int BlockSelectSort(RandomAccessIterator array, int firstKey, int start, int medianKey, int blockCount, int blockLen, Compare comp) {
for (int firstBlock = 0; firstBlock < blockCount; firstBlock++) {
int selectBlock = firstBlock;
for (int currBlock = firstBlock + 1; currBlock < blockCount; currBlock++) {
int compare = comp(array[start + (currBlock * blockLen)],
array[start + (selectBlock * blockLen)]);
if (compare < 0 || (compare == 0 && comp(array[firstKey + currBlock],
array[firstKey + selectBlock]) < 0)) {
selectBlock = currBlock;
}
}
if (selectBlock != firstBlock) {
// Swap the left and right selected blocks...
BlockSwap(array, start + (firstBlock * blockLen), start + (selectBlock * blockLen), blockLen);
// Swap the keys...
std::swap(array[firstKey + firstBlock], array[firstKey + selectBlock]);
// ...and follow the 'medianKey' if it was swapped
// ORIGINAL LOC: if(midkey==u-1 || midkey==p) midkey^=(u-1)^p;
// MASSIVE, MASSIVE credit to lovebuny for figuring this one out!
if (medianKey == firstBlock) {
medianKey = selectBlock;
}
else if (medianKey == selectBlock) {
medianKey = firstBlock;
}
}
}
return medianKey;
}
// Swaps Grailsort's "scrolling buffer" from the right side of the array all the way back to 'start'.
// Costs O(n) swaps (amortized).
//
// OFF-BY-ONE BUG FIXED: used to be `int index = start + resetLen`; credit to 666666t for debugging
// RESTRUCTED, BETTER NAMES: 'resetLen' is now 'length' and 'bufferLen' is now 'bufferOffset'
template<typename RandomAccessIterator>
static void InPlaceBufferReset(RandomAccessIterator array, int start, int length, int bufferOffset) {
int index = start + length - 1;
int buffer = index - bufferOffset;
while (index >= start) {
std::swap(array[index], array[buffer]);
index--;
buffer--;
}
}
// Shifts entire array over 'bufferOffset' spaces to move the out-of-place merging buffer back to
// the beginning of the array.
// Costs O(n) writes (amortized).
//
// OFF-BY-ONE BUG FIXED: used to be `int index = start + resetLen`; credit to 666666t for debugging
// RESTRUCTED, BETTER NAMES: 'resetLen' is now 'length' and 'bufferLen' is now 'bufferOffset'
template<typename RandomAccessIterator>
static void OutOfPlaceBufferReset(RandomAccessIterator array, int start, int length, int bufferOffset) {
int index = start + length - 1;
int buffer = index - bufferOffset;
while (index >= start) {
array[index] = std::move(array[buffer]);
index--;
buffer--;
}
}
// Rewinds Grailsort's "scrolling buffer" to the left any items belonging to the left subarray block
// left over by a "smart merge". This is used to continue an ongoing merge that has run out of buffer space.
// Costs O(sqrt n) swaps (amortized) in the *absolute* worst-case.
//
// NAMING IMPROVED: the left over items are in the middle of the merge while the buffer is at the end
// BETTER ORDER-OF-OPERATIONS, NAMING IMPROVED: the left over items (now called 'leftBlock') are in the
// middle of the merge while the buffer is at the end
template<typename RandomAccessIterator>
static void InPlaceBufferRewind(RandomAccessIterator array, int start, int leftBlock, int buffer) {
while (leftBlock >= start) {
std::swap(array[buffer], array[leftBlock]);
leftBlock--;
buffer--;
}
}
// Rewinds Grailsort's out-of-place buffer to the left of any items belonging to the left subarray block
// left over by a "smart merge". This is used to continue an ongoing merge that has run out of buffer space.
// Costs O(sqrt n) writes (amortized) in the *absolute* worst-case.
//
// INCORRECT ORDER OF PARAMETERS BUG FIXED: `leftOvers` should be the middle, and `buffer` should be the end
// BETTER ORDER, INCORRECT ORDER OF PARAMETERS BUG FIXED: `leftOvers` (now called 'leftBlock') should be
// the middle, and `buffer` should be the end
template<typename RandomAccessIterator>
static void OutOfPlaceBufferRewind(RandomAccessIterator array, int start, int leftBlock, int buffer) {
while (leftBlock >= start) {
array[buffer] = std::move(array[leftBlock]);
leftBlock--;
buffer--;
}
}
template<typename RandomAccessIterator, typename Compare>
static Subarray GetSubarray(RandomAccessIterator array, int currKey, int medianKey, Compare comp) {
if (comp(array[currKey], array[medianKey]) < 0) {
return Subarray::LEFT;
}
else {
return Subarray::RIGHT;
}
}
// FUNCTION RE-RENAMED: last/final left blocks are used to calculate the length of the final merge
template<typename RandomAccessIterator, typename Compare>
static int CountLastMergeBlocks(RandomAccessIterator array, int offset, int blockCount, int blockLen, Compare comp) {
int blocksToMerge = 0;
int lastRightFrag = offset + (blockCount * blockLen);
int prevLeftBlock = lastRightFrag - blockLen;
while (blocksToMerge < blockCount && comp(array[lastRightFrag], array[prevLeftBlock]) < 0) {
blocksToMerge++;
prevLeftBlock -= blockLen;
}
return blocksToMerge;
}
template<typename RandomAccessIterator, typename Compare>
void SmartMerge(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, int bufferOffset, Compare comp) {
auto buffer = array + (start - bufferOffset);
auto left = array + start;
auto middle = left + leftLen;
auto right = middle;
auto end = middle + rightLen;
if (leftOrigin == Subarray::LEFT) {
while (left != middle && right != end) {
if (comp(*left, *right) <= 0) {
std::iter_swap(buffer, left);
++left;
}
else {
std::iter_swap(buffer, right);
++right;
}
++buffer;
}
}
else {
while (left != middle && right != end) {
if (comp(*left, *right) < 0) {
std::iter_swap(buffer, left);
++left;
}
else {
std::iter_swap(buffer, right);
++right;
}
++buffer;
}
}
if (left < middle) {
this->currBlockLen = middle - left;
// UPDATED ARGUMENTS: 'middle' and 'end' now 'middle - 1' and 'end - 1'
InPlaceBufferRewind(array, left - array, (middle - array) - 1, (end - array) - 1);
}
else {
this->currBlockLen = end - right;
if (leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
}
// MINOR CHANGE: better naming -- 'insertPos' is now 'mergeLen' -- and "middle" calculation simplified
template<typename RandomAccessIterator, typename Compare>
void SmartLazyMerge(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, Compare comp) {
int middle = start + leftLen;
if (leftOrigin == Subarray::LEFT) {
if (comp(array[middle - 1], array[middle]) > 0) {
while (leftLen != 0) {
int mergeLen = BinarySearchLeft(array, middle, rightLen, array[start], comp);
if (mergeLen != 0) {
Rotate(array, start, leftLen, mergeLen);
start += mergeLen;
rightLen -= mergeLen;
}
middle += mergeLen;
if (rightLen == 0) {
this->currBlockLen = leftLen;
return;
}
else {
do {
start++;
leftLen--;
} while (leftLen != 0 && comp(array[start], array[middle]) <= 0);
}
}
}
}
else {
if (comp(array[middle - 1], array[middle]) >= 0) {
while (leftLen != 0) {
int mergeLen = BinarySearchRight(array, start + leftLen, rightLen, array[start], comp);
if (mergeLen != 0) {
Rotate(array, start, leftLen, mergeLen);
start += mergeLen;
rightLen -= mergeLen;
}
middle += mergeLen;
if (rightLen == 0) {
this->currBlockLen = leftLen;
return;
}
else {
do {
start++;
leftLen--;
} while (leftLen != 0 && comp(array[start], array[middle]) < 0);
}
}
}
}
this->currBlockLen = rightLen;
if (leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
// FUNCTION RENAMED: more consistent with other "out-of-place" merges
template<typename RandomAccessIterator, typename Compare>
void SmartMergeOutOfPlace(RandomAccessIterator array, int start, int leftLen, Subarray leftOrigin, int rightLen, int bufferOffset, Compare comp) {
int buffer = start - bufferOffset;
int left = start;
int middle = start + leftLen;
int right = middle;
int end = middle + rightLen;
if (leftOrigin == Subarray::LEFT) {
while (left < middle && right < end) {
if (comp(array[left], array[right]) <= 0) {
array[buffer] = std::move(array[left]);
left++;
}
else {
array[buffer] = std::move(array[right]);
right++;
}
buffer++;
}
}
else {
while (left < middle && right < end) {
if (comp(array[left], array[right]) < 0) {
array[buffer] = std::move(array[left]);
left++;
}
else {
array[buffer] = std::move(array[right]);
right++;
}
buffer++;
}
}
if (left < middle) {
this->currBlockLen = middle - left;
// UPDATED ARGUMENTS: 'middle' and 'end' now 'middle - 1' and 'end - 1'
OutOfPlaceBufferRewind(array, left, middle - 1, end - 1);
}
else {
this->currBlockLen = end - right;
if (leftOrigin == Subarray::LEFT) {
this->currBlockOrigin = Subarray::RIGHT;
}
else {
this->currBlockOrigin = Subarray::LEFT;
}
}
}
// Credit to Anonymous0726 for better variable names such as "nextBlock"
// Also minor change: removed unnecessary "currBlock = nextBlock" lines
template<typename RandomAccessIterator, typename Compare>
void MergeBlocks(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int buffer;
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for (int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if (nextBlockOrigin == this->currBlockOrigin) {
buffer = currBlock - blockLen;
BlockSwap(array, buffer, currBlock, this->currBlockLen);
this->currBlockLen = blockLen;
}
else {
SmartMerge(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, blockLen, comp);
}
}
currBlock = nextBlock - this->currBlockLen;
buffer = currBlock - blockLen;
if (lastLen != 0) {
if (this->currBlockOrigin == Subarray::RIGHT) {
BlockSwap(array, buffer, currBlock, this->currBlockLen);
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
MergeForwards(array, currBlock, this->currBlockLen, lastLen, blockLen, comp);
}
else {
BlockSwap(array, buffer, currBlock, this->currBlockLen);
}
}
template<typename RandomAccessIterator, typename Compare>
void LazyMergeBlocks(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for (int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if (nextBlockOrigin == this->currBlockOrigin) {
this->currBlockLen = blockLen;
}
else {
// These checks were included in the original code... but why???
if (blockLen != 0 && this->currBlockLen != 0) {
SmartLazyMerge(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, comp);
}
}
}
currBlock = nextBlock - this->currBlockLen;
if (lastLen != 0) {
if (this->currBlockOrigin == Subarray::RIGHT) {
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
LazyMerge(array, currBlock, this->currBlockLen, lastLen, comp);
}
}
template<typename RandomAccessIterator, typename Compare>
void MergeBlocksOutOfPlace(RandomAccessIterator array, int firstKey, int medianKey, int start, int blockCount, int blockLen,
int lastMergeBlocks, int lastLen, Compare comp) {
int buffer;
int currBlock;
int nextBlock = start + blockLen;
this->currBlockLen = blockLen;
this->currBlockOrigin = GetSubarray(array, firstKey, medianKey, comp);
Subarray nextBlockOrigin;
for (int keyIndex = 1; keyIndex < blockCount; keyIndex++, nextBlock += blockLen) {
currBlock = nextBlock - this->currBlockLen;
nextBlockOrigin = GetSubarray(array, firstKey + keyIndex, medianKey, comp);
if (nextBlockOrigin == this->currBlockOrigin) {
buffer = currBlock - blockLen;
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
this->currBlockLen = blockLen;
}
else {
SmartMergeOutOfPlace(array, currBlock, this->currBlockLen, this->currBlockOrigin, blockLen, blockLen, comp);
}
}
currBlock = nextBlock - this->currBlockLen;
buffer = currBlock - blockLen;
if (lastLen != 0) {
if (this->currBlockOrigin == Subarray::RIGHT) {
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
currBlock = nextBlock;
this->currBlockLen = blockLen * lastMergeBlocks;
this->currBlockOrigin = Subarray::LEFT;
}
else {
this->currBlockLen += blockLen * lastMergeBlocks;
}
MergeOutOfPlace(array, currBlock, this->currBlockLen, lastLen, blockLen, comp);
}
else {
std::move(array + currBlock, array + (currBlock + this->currBlockLen), array + buffer);
}
}
//TODO: Double-check "Merge Blocks" arguments
template<typename RandomAccessIterator, typename Compare>
void CombineInPlace(RandomAccessIterator array, int firstKey, int start, int length, int subarrayLen, int blockLen,
int mergeCount, int lastSubarrays, bool buffer, Compare comp) {
int fullMerge = 2 * subarrayLen;
// SLIGHT OPTIMIZATION: 'blockCount' only needs to be calculated once for regular merges
int blockCount = fullMerge / blockLen;
for (int mergeIndex = 0; mergeIndex < mergeCount; mergeIndex++) {
int offset = start + (mergeIndex * fullMerge);
InsertSort(array, firstKey, blockCount, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
if (buffer) {
MergeBlocks(array, firstKey, firstKey + medianKey, offset, blockCount, blockLen, 0, 0, comp);
}
else {
LazyMergeBlocks(array, firstKey, firstKey + medianKey, offset, blockCount, blockLen, 0, 0, comp);
}
}
// INCORRECT CONDITIONAL/PARAMETER BUG FIXED: Credit to 666666t for debugging.
if (lastSubarrays != 0) {
int offset = start + (mergeCount * fullMerge);
blockCount = lastSubarrays / blockLen;
InsertSort(array, firstKey, blockCount + 1, comp);
// INCORRECT PARAMETER BUG FIXED: `block select sort` should be using `offset`, not `start`
int medianKey = subarrayLen / blockLen;
medianKey = BlockSelectSort(array, firstKey, offset, medianKey, blockCount, blockLen, comp);
// MISSING BOUNDS CHECK BUG FIXED: `lastFragment` *can* be 0 if the last two subarrays are evenly
// divided into blocks. This prevents Grailsort from going out-of-bounds.
int lastFragment = lastSubarrays - (blockCount * blockLen);
int lastMergeBlocks;
if (lastFragment != 0) {
lastMergeBlocks = CountLastMergeBlocks(array, offset, blockCount, blockLen, comp);
}
else {
lastMergeBlocks = 0;
}
int smartMerges = blockCount - lastMergeBlocks;
//TODO: Double-check if this micro-optimization works correctly like the original
if (smartMerges == 0) {
int leftLen = lastMergeBlocks * blockLen;
// INCORRECT PARAMETER BUG FIXED: these merges should be using `offset`, not `start`
if (buffer) {
MergeForwards(array, offset, leftLen, lastFragment, blockLen, comp);
}
else {
LazyMerge(array, offset, leftLen, lastFragment, comp);
}
}
else {
if (buffer) {
MergeBlocks(array, firstKey, firstKey + medianKey, offset,
smartMerges, blockLen, lastMergeBlocks, lastFragment, comp);
}