forked from BonzaiThePenguin/WikiSort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWikiSort.c
1765 lines (1556 loc) · 66.8 KB
/
WikiSort.c
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
/***********************************************************
WikiSort (public domain license)
https://github.com/BonzaiThePenguin/WikiSort
to run:
clang -o WikiSort.x WikiSort.c -O3
(or replace 'clang' with 'gcc')
./WikiSort.x
***********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <limits.h>
/* record the number of comparisons */
/* note that this reduces WikiSort's performance when enabled */
#define PROFILE true
/* verify that WikiSort is actually correct */
/* (this also reduces performance slightly) */
#define VERIFY true
/* simulate comparisons that have a bit more overhead than just an inlined (int < int) */
/* (so we can tell whether reducing the number of comparisons was worth the added complexity) */
#define SLOW_COMPARISONS false
/* whether to give WikiSort a full-size cache, to see how it performs when given more memory */
#define DYNAMIC_CACHE false
double Seconds()
{
return clock() * 1.0 / CLOCKS_PER_SEC;
}
/* various #defines for the C code */
#ifndef true
#define true 1
#define false 0
typedef uint8_t bool;
#endif
#define Var(name, value) __typeof__(value) name = value
#define Allocate(type, count) (type *)malloc((count) * sizeof(type))
size_t Min(const size_t a, const size_t b)
{
return (a <= b) ? a : b;
}
size_t Max(const size_t a, const size_t b)
{
return (a > b) ? a : b;
}
/* structure to test stable sorting (index will contain its original index in the array, to make sure it doesn't switch places with other items) */
typedef struct
{
size_t value;
#if VERIFY
size_t index;
#endif
} Test;
#if PROFILE
/* global for testing how many comparisons are performed for each sorting algorithm */
static size_t comparisons;
#endif
#if SLOW_COMPARISONS
#define NOOP_SIZE 50
size_t noop1[NOOP_SIZE], noop2[NOOP_SIZE];
#endif
int new_compare(const void *item1, const void *item2)
{
const Test *_item1 = (const Test *)item1;
const Test *_item2 = (const Test *)item2;
#if SLOW_COMPARISONS
/* test slow comparisons by adding some fake overhead */
/* (in real-world use this might be string comparisons, etc.) */
size_t index;
for (index = 0; index < NOOP_SIZE; index++)
{
noop1[index] = noop2[index];
}
#endif
#if PROFILE
comparisons++;
#endif
return (_item1->value - _item2->value);
}
bool TestCompare(Test item1, Test item2)
{
return new_compare(&item1, &item2) < 0;
}
typedef int (*Comparison)(const void *, const void*);
/* structure to represent ranges within the array */
typedef struct
{
size_t start;
size_t end;
} Range;
size_t Range_length(Range range)
{
return range.end - range.start;
}
Range Range_new(const size_t start, const size_t end)
{
Range range;
range.start = start;
range.end = end;
return range;
}
/* toolbox functions used by the sorter */
/* Byte-wise swap two items of size SIZE. */
#define Swap(a, b, size) \
do \
{ \
size_t __size = (size); \
char *__a = (char *)(a); \
char *__b = (char *)(b); \
do \
{ \
char __tmp = *__a; \
*__a++ = *__b; \
*__b++ = __tmp; \
} while (--__size > 0); \
} while (0)
/* 63 -> 32, 64 -> 64, etc. */
/* this comes from Hacker's Delight */
size_t FloorPowerOfTwo(const size_t value)
{
size_t x = value;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
#if __LP64__
x = x | (x >> 32);
#endif
return x - (x >> 1);
}
/* find the index of the first value within the range that is equal to array[index] */
size_t BinaryFirst(char *array, char *value, size_t size, const Range range, const Comparison compare)
{
size_t start = range.start, end = range.end - 1;
if (range.start >= range.end)
{
return range.start;
}
while (start < end)
{
size_t mid = start + (end - start) / 2;
if (compare(&array[size * mid], value) < 0)
{
start = mid + 1;
}
else
{
end = mid;
}
}
if (start == range.end - 1 && compare(&array[size * start], value) < 0)
{
start++;
}
return start;
}
/* find the index of the last value within the range that is equal to array[index], plus 1 */
size_t BinaryLast(char *array, char *value, size_t size, const Range range, const Comparison compare)
{
size_t start = range.start, end = range.end - 1;
if (range.start >= range.end)
{
return range.end;
}
while (start < end)
{
size_t mid = start + (end - start) / 2;
if (compare(value, &array[size * mid]) >= 0)
{
start = mid + 1;
}
else
{
end = mid;
}
}
if (start == range.end - 1 && compare(value, &array[size * start]) >= 0)
{
start++;
}
return start;
}
/* combine a linear search with a binary search to reduce the number of comparisons in situations */
/* where have some idea as to how many unique values there are and where the next value might be */
size_t FindFirstForward(char *array, char *value, size_t size, const Range range, const Comparison compare, const size_t unique)
{
size_t skip, index;
if (Range_length(range) == 0)
{
return range.start;
}
skip = Max(Range_length(range) / unique, 1);
for (index = range.start + skip; compare(&array[size * (index - 1)], value) < 0; index += skip)
{
if (index >= range.end - skip)
{
return BinaryFirst(array, value, size, Range_new(index, range.end), compare);
}
}
return BinaryFirst(array, value, size, Range_new(index - skip, index), compare);
}
size_t FindLastForward(char *array, char *value, size_t size, const Range range, const Comparison compare, const size_t unique)
{
size_t skip, index;
if (Range_length(range) == 0)
{
return range.start;
}
skip = Max(Range_length(range) / unique, 1);
for (index = range.start + skip; compare(value, &array[size * (index - 1)]) >= 0; index += skip)
{
if (index >= range.end - skip)
{
return BinaryLast(array, value, size, Range_new(index, range.end), compare);
}
}
return BinaryLast(array, value, size, Range_new(index - skip, index), compare);
}
size_t FindFirstBackward(char *array, char *value, size_t size, const Range range, const Comparison compare, const size_t unique)
{
size_t skip, index;
if (Range_length(range) == 0)
{
return range.start;
}
skip = Max(Range_length(range) / unique, 1);
for (index = range.end - skip; index > range.start && compare(&array[size * (index - 1)], value) >= 0; index -= skip)
{
if (index < range.start + skip)
{
return BinaryFirst(array, value, size, Range_new(range.start, index), compare);
}
}
return BinaryFirst(array, value, size, Range_new(index, index + skip), compare);
}
size_t FindLastBackward(char *array, char *value, size_t size, const Range range, const Comparison compare, const size_t unique)
{
size_t skip, index;
if (Range_length(range) == 0)
{
return range.start;
}
skip = Max(Range_length(range) / unique, 1);
for (index = range.end - skip; index > range.start && compare(value, &array[size * (index - 1)]) < 0; index -= skip)
{
if (index < range.start + skip)
{
return BinaryLast(array, value, size, Range_new(range.start, index), compare);
}
}
return BinaryLast(array, value, size, Range_new(index, index + skip), compare);
}
/* n^2 sorting algorithm used to sort tiny chunks of the full array */
void InsertionSort(char *array, size_t size, const Range range, const Comparison compare)
{
size_t i, j;
for (i = range.start + 1; i < range.end; i++)
{
for (j = i; j > range.start && compare(&array[size * j], &array[size * (j - 1)]) < 0; j--)
{
Swap(&array[size * j], &array[size * (j - 1)], size);
}
}
}
/* reverse a range of values within the array */
void Reverse(char *array, size_t size, const Range range)
{
size_t index;
for (index = Range_length(range) / 2; index > 0; index--)
{
Swap(&array[size * (range.start + index - 1)], &array[size * (range.end - index)], size);
}
}
/* swap a series of values in the array */
void BlockSwap(char *array, size_t size, const size_t start1, const size_t start2, const size_t block_size)
{
size_t index;
for (index = 0; index < block_size; index++)
{
Swap(&array[size * (start1 + index)], &array[size * (start2 + index)], size);
}
}
/* rotate the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1) */
/* this assumes that 0 <= amount <= range.length() */
void Rotate(char *array, size_t size, const size_t amount, const Range range, char *cache, const size_t cache_size)
{
size_t split;
Range range1, range2;
if (Range_length(range) == 0)
{
return;
}
split = range.start + amount;
range1 = Range_new(range.start, split);
range2 = Range_new(split, range.end);
// if the smaller of the two ranges fits into the cache, it's *slightly* faster copying it there and shifting the elements over
if (Range_length(range1) <= Range_length(range2))
{
if (Range_length(range1) <= cache_size)
{
memcpy(cache, &array[size * range1.start], Range_length(range1) * size);
memmove(&array[size * range1.start], &array[size * range2.start], Range_length(range2) * size);
memcpy(&array[size * (range1.start + Range_length(range2))], cache, Range_length(range1) * size);
return;
}
}
else
{
if (Range_length(range2) <= cache_size)
{
memcpy(cache, &array[size * range2.start], Range_length(range2) * size);
memmove(&array[size * (range2.end - Range_length(range1))], &array[size * range1.start], Range_length(range1) * size);
memcpy(&array[size * range1.start], cache, Range_length(range2) * size);
return;
}
}
Reverse(array, size, range1);
Reverse(array, size, range2);
Reverse(array, size, range);
}
/* calculate how to scale the index value to the range within the array */
/* the bottom-up merge sort only operates on values that are powers of two, */
/* so scale down to that power of two, then use a fraction to scale back again */
typedef struct
{
size_t size, power_of_two;
size_t numerator, decimal;
size_t denominator, decimal_step, numerator_step;
} WikiIterator;
void WikiIterator_begin(WikiIterator *me)
{
me->numerator = me->decimal = 0;
}
Range WikiIterator_nextRange(WikiIterator *me)
{
size_t start = me->decimal;
me->decimal += me->decimal_step;
me->numerator += me->numerator_step;
if (me->numerator >= me->denominator)
{
me->numerator -= me->denominator;
me->decimal++;
}
return Range_new(start, me->decimal);
}
bool WikiIterator_finished(WikiIterator *me)
{
return (me->decimal >= me->size);
}
bool WikiIterator_nextLevel(WikiIterator *me)
{
me->decimal_step += me->decimal_step;
me->numerator_step += me->numerator_step;
if (me->numerator_step >= me->denominator)
{
me->numerator_step -= me->denominator;
me->decimal_step++;
}
return (me->decimal_step < me->size);
}
size_t WikiIterator_length(WikiIterator *me)
{
return me->decimal_step;
}
WikiIterator WikiIterator_new(size_t size2, size_t min_level)
{
WikiIterator me;
me.size = size2;
me.power_of_two = FloorPowerOfTwo(me.size);
me.denominator = me.power_of_two / min_level;
me.numerator_step = me.size % me.denominator;
me.decimal_step = me.size / me.denominator;
WikiIterator_begin(&me);
return me;
}
/* merge two ranges from one array and save the results into a different array */
void MergeInto(char *from, size_t size, const Range A, const Range B, const Comparison compare, char *into)
{
char *A_index = &from[size * A.start];
char *B_index = &from[size * B.start];
char *A_last = &from[size * A.end];
char *B_last = &from[size * B.end];
char *insert_index = into;
while (true)
{
if (compare(B_index, A_index) >= 0)
{
memcpy(insert_index, A_index, size);
A_index += size;
insert_index += size;
if (A_index == A_last)
{
// copy the remainder of B into the final array
memcpy(insert_index, B_index, (B_last - B_index));
break;
}
}
else
{
memcpy(insert_index, B_index, size);
B_index += size;
insert_index += size;
if (B_index == B_last)
{
// copy the remainder of A into the final array
memcpy(insert_index, A_index, (A_last - A_index));
break;
}
}
}
}
/* merge operation using an external buffer, */
void MergeExternal(char *array, size_t size, const Range A, const Range B, const Comparison compare, char *cache)
{
/* A fits into the cache, so use that instead of the internal buffer */
char *A_index = &cache[0];
char *B_index = &array[size * B.start];
char *insert_index = &array[size * A.start];
char *A_last = &cache[size * Range_length(A)];
char *B_last = &array[size * B.end];
if (Range_length(B) > 0 && Range_length(A) > 0)
{
while (true)
{
if (compare(B_index, A_index) >= 0)
{
memcpy(insert_index, A_index, size);
A_index += size;
insert_index += size;
if (A_index == A_last)
{
break;
}
}
else
{
memcpy(insert_index, B_index, size);
B_index += size;
insert_index += size;
if (B_index == B_last)
{
break;
}
}
}
}
/* copy the remainder of A into the final array */
memcpy(insert_index, A_index, (A_last - A_index));
}
/* merge operation using an internal buffer */
void MergeInternal(char *array, size_t size, const Range A, const Range B, const Comparison compare, const Range buffer)
{
// whenever we find a value to add to the final array, swap it with the value that's already in that spot
// when this algorithm is finished, 'buffer' will contain its original contents, but in a different order
size_t A_count = 0;
size_t B_count = 0;
size_t insert = 0;
if (Range_length(B) > 0 && Range_length(A) > 0)
{
while (true)
{
if (compare(&array[size * (B.start + B_count)], &array[size * (buffer.start + A_count)]) >= 0)
{
Swap(&array[size * (A.start + insert)], &array[size * (buffer.start + A_count)], size);
A_count++;
insert++;
if (A_count >= Range_length(A))
{
break;
}
}
else
{
Swap(&array[size * (A.start + insert)], &array[size * (B.start + B_count)], size);
B_count++;
insert++;
if (B_count >= Range_length(B))
{
break;
}
}
}
}
// swap the remainder of A into the final array
BlockSwap(array, size, buffer.start + A_count, A.start + insert, Range_length(A) - A_count);
}
/* merge operation without a buffer */
void MergeInPlace(char *array, size_t size, Range A, Range B, const Comparison compare, char *cache, const size_t cache_size)
{
if (Range_length(A) == 0 || Range_length(B) == 0)
{
return;
}
// this just repeatedly binary searches into B and rotates A into position.
// the paper suggests using the 'rotation-based Hwang and Lin algorithm' here,
// but I decided to stick with this because it had better situational performance
// (Hwang and Lin is designed for merging subarrays of very different sizes,
// but WikiSort almost always uses subarrays that are roughly the same size)
// normally this is incredibly suboptimal, but this function is only called
// when none of the A or B blocks in any subarray contained 2√A unique values,
// which places a hard limit on the number of times this will ACTUALLY need
// to binary search and rotate.
// according to my analysis the worst case is √A rotations performed on √A items
// once the constant factors are removed, which ends up being O(n)
// again, this is NOT a general-purpose solution – it only works well in this case!
// kind of like how the O(n^2) insertion sort is used in some places
while (true)
{
// find the first place in B where the first item in A needs to be inserted
size_t mid = BinaryFirst(array, &array[size * A.start], size, B, compare);
// rotate A into place
size_t amount = mid - A.end;
Rotate(array, size, Range_length(A), Range_new(A.start, mid), cache, cache_size);
if (B.end == mid)
{
break;
}
// calculate the new A and B ranges
B.start = mid;
A = Range_new(A.start + amount, B.start);
A.start = BinaryLast(array, &array[size * A.start], size, A, compare);
if (Range_length(A) == 0)
{
break;
}
}
}
/* bottom-up merge sort combined with an in-place merge algorithm for O(1) memory use */
void new_WikiSort(char *array, const size_t len, const size_t size, const Comparison compare)
{
// use a small cache to speed up some of the operations
#if DYNAMIC_CACHE
size_t cache_size;
char *cache = NULL;
#else
// since the cache size is fixed, it's still O(1) memory!
// just keep in mind that making it too small ruins the point (nothing will fit into it),
// and making it too large also ruins the point (so much for "low memory"!)
// removing the cache entirely still gives 70% of the performance of a standard merge
#define CACHE_SIZE 0
const size_t cache_size = CACHE_SIZE;
//char cache[CACHE_SIZE*sizeof(Test)];
char *cache = NULL;
#endif
WikiIterator iterator;
// if the array is of len 0, 1, 2, or 3, just sort them like so:
if (len < 4)
{
if (len == 3)
{
// hard-coded insertion sort
if (compare(&array[size * 1], &array[size * 0]) < 0)
{
Swap(&array[size * 0], &array[size * 1], size);
}
if (compare(&array[size * 2], &array[size * 1]) < 0)
{
Swap(&array[size * 1], &array[size * 2], size);
if (compare(&array[size * 1], &array[size * 0]) < 0)
{
Swap(&array[size * 0], &array[size * 1], size);
}
}
}
else if (len == 2)
{
// swap the items if they're out of order
if (compare(&array[size * 1], &array[size * 0]) < 0)
{
Swap(&array[size * 0], &array[size * 1], size);
}
}
return;
}
// sort groups of 4-8 items at a time using an unstable sorting network,
// but keep track of the original item orders to force it to be stable
// http://pages.ripco.net/~jgamble/nw.html
iterator = WikiIterator_new(len, 4);
WikiIterator_begin(&iterator);
while (!WikiIterator_finished(&iterator))
{
uint8_t order[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
Range range = WikiIterator_nextRange(&iterator);
#define NEW_SWAP(x, y) \
do \
{ \
if ( (compare(&array[size * (range.start + y)], &array[size * (range.start + x)]) < 0) \
|| ( (order[x] > order[y]) \
&& (compare(&array[size * (range.start + x)], &array[size * (range.start + y)]) >= 0))) \
{ \
Swap(&array[size * (range.start + x)], &array[size * (range.start + y)], size); \
Swap(&order[x], &order[y], 1); \
} \
} \
while (0)
if (Range_length(range) == 8)
{
NEW_SWAP(0, 1);
NEW_SWAP(2, 3);
NEW_SWAP(4, 5);
NEW_SWAP(6, 7);
NEW_SWAP(0, 2);
NEW_SWAP(1, 3);
NEW_SWAP(4, 6);
NEW_SWAP(5, 7);
NEW_SWAP(1, 2);
NEW_SWAP(5, 6);
NEW_SWAP(0, 4);
NEW_SWAP(3, 7);
NEW_SWAP(1, 5);
NEW_SWAP(2, 6);
NEW_SWAP(1, 4);
NEW_SWAP(3, 6);
NEW_SWAP(2, 4);
NEW_SWAP(3, 5);
NEW_SWAP(3, 4);
}
else if (Range_length(range) == 7)
{
NEW_SWAP(1, 2);
NEW_SWAP(3, 4);
NEW_SWAP(5, 6);
NEW_SWAP(0, 2);
NEW_SWAP(3, 5);
NEW_SWAP(4, 6);
NEW_SWAP(0, 1);
NEW_SWAP(4, 5);
NEW_SWAP(2, 6);
NEW_SWAP(0, 4);
NEW_SWAP(1, 5);
NEW_SWAP(0, 3);
NEW_SWAP(2, 5);
NEW_SWAP(1, 3);
NEW_SWAP(2, 4);
NEW_SWAP(2, 3);
}
else if (Range_length(range) == 6)
{
NEW_SWAP(1, 2);
NEW_SWAP(4, 5);
NEW_SWAP(0, 2);
NEW_SWAP(3, 5);
NEW_SWAP(0, 1);
NEW_SWAP(3, 4);
NEW_SWAP(2, 5);
NEW_SWAP(0, 3);
NEW_SWAP(1, 4);
NEW_SWAP(2, 4);
NEW_SWAP(1, 3);
NEW_SWAP(2, 3);
}
else if (Range_length(range) == 5)
{
NEW_SWAP(0, 1);
NEW_SWAP(3, 4);
NEW_SWAP(2, 4);
NEW_SWAP(2, 3);
NEW_SWAP(1, 4);
NEW_SWAP(0, 3);
NEW_SWAP(0, 2);
NEW_SWAP(1, 3);
NEW_SWAP(1, 2);
}
else if (Range_length(range) == 4)
{
NEW_SWAP(0, 1);
NEW_SWAP(2, 3);
NEW_SWAP(0, 2);
NEW_SWAP(1, 3);
NEW_SWAP(1, 2);
}
}
if (len < 8)
{
return;
}
#if DYNAMIC_CACHE
// good choices for the cache len are:
// (len + 1)/2 – turns into a full-speed standard merge sort since everything fits into the cache
cache_size = (len + 1) / 2;
cache = malloc(cache_size * size);
if (!cache)
{
// sqrt((len + 1)/2) + 1 – this will be the len of the A blocks at the largest level of merges,
// so a buffer of this len would allow it to skip using internal or in-place merges for anything
cache_size = sqrt(cache_size) + 1;
cache = malloc(cache_size * size);
if (!cache)
{
// 512 – chosen from careful testing as a good balance between fixed-len memory use and run time
if (cache_size > 512)
{
cache_size = 512;
cache = malloc(cache_size * size);
}
// 0 – if the system simply cannot allocate any extra memory whatsoever, no memory works just fine
if (!cache)
{
cache_size = 0;
}
}
}
#endif
// then merge sort the higher levels, which can be 8-15, 16-31, 32-63, 64-127, etc.
while (true)
{
// if every A and B block will fit into the cache, use a special branch specifically for merging with the cache
// (we use < rather than <= since the block len might be one more than iterator.length())
if (WikiIterator_length(&iterator) < cache_size)
{
// if four subarrays fit into the cache, it's faster to merge both pairs of subarrays into the cache,
// then merge the two merged subarrays from the cache back into the original array
if ((WikiIterator_length(&iterator) + 1) * 4 <= cache_size && WikiIterator_length(&iterator) * 4 <= len)
{
WikiIterator_begin(&iterator);
while (!WikiIterator_finished(&iterator))
{
// merge A1 and B1 into the cache
Range A1, B1, A2, B2, A3, B3;
A1 = WikiIterator_nextRange(&iterator);
B1 = WikiIterator_nextRange(&iterator);
A2 = WikiIterator_nextRange(&iterator);
B2 = WikiIterator_nextRange(&iterator);
if (compare(&array[size * (B1.end - 1)], &array[size * A1.start]) < 0)
{
// the two ranges are in reverse order, so copy them in reverse order into the cache
memcpy(&cache[size * Range_length(B1)], &array[size * A1.start], Range_length(A1) * size);
memcpy(&cache[0], &array[size * B1.start], Range_length(B1) * size);
}
else if (compare(&array[size * B1.start], &array[size * (A1.end - 1)]) < 0)
{
// these two ranges weren't already in order, so merge them into the cache
MergeInto(array, size, A1, B1, compare, &cache[0]);
}
else
{
// if A1, B1, A2, and B2 are all in order, skip doing anything else
if ( (compare(&array[size * B2.start], &array[size * (A2.end - 1)]) >= 0)
&& (compare(&array[size * A2.start], &array[size * (B1.end - 1)]) >= 0))
{
continue;
}
// copy A1 and B1 into the cache in the same order
memcpy(&cache[0], &array[size * A1.start], Range_length(A1) * size);
memcpy(&cache[size * Range_length(A1)], &array[size * B1.start], Range_length(B1) * size);
}
A1 = Range_new(A1.start, B1.end);
// merge A2 and B2 into the cache
if (compare(&array[size * (B2.end - 1)], &array[size * A2.start]) < 0)
{
// the two ranges are in reverse order, so copy them in reverse order into the cache
memcpy(&cache[size * (Range_length(A1) + Range_length(B2))], &array[size * A2.start], Range_length(A2) * size);
memcpy(&cache[size * Range_length(A1)], &array[size * B2.start], Range_length(B2) * size);
}
else if (compare(&array[size * B2.start], &array[size * (A2.end - 1)]))
{
// these two ranges weren't already in order, so merge them into the cache
MergeInto(array, size, A2, B2, compare, &cache[size * Range_length(A1)]);
}
else
{
// copy A2 and B2 into the cache in the same order
memcpy(&cache[size * Range_length(A1)], &array[size * A2.start], Range_length(A2) * size);
memcpy(&cache[size * (Range_length(A1) + Range_length(A2))], &array[size * B2.start], Range_length(B2) * size);
}
A2 = Range_new(A2.start, B2.end);
// merge A1 and A2 from the cache into the array
A3 = Range_new(0, Range_length(A1));
B3 = Range_new(Range_length(A1), Range_length(A1) + Range_length(A2));
if (compare(&cache[size * (B3.end - 1)], &cache[size * A3.start]) < 0)
{
// the two ranges are in reverse order, so copy them in reverse order into the array
memcpy(&array[size * (A1.start + Range_length(A2))], &cache[size * A3.start], Range_length(A3) * size);
memcpy(&array[size * A1.start], &cache[size * B3.start], Range_length(B3) * size);
}
else if (compare(&cache[size * B3.start], &cache[size * (A3.end - 1)]) < 0)
{
// these two ranges weren't already in order, so merge them back into the array
MergeInto(cache, size, A3, B3, compare, &array[size * A1.start]);
}
else
{
// copy A3 and B3 into the array in the same order
memcpy(&array[size * A1.start], &cache[size * A3.start], Range_length(A3) * size);
memcpy(&array[size * (A1.start + Range_length(A1))], &cache[size * B3.start], Range_length(B3) * size);
}
}
// we merged two levels at the same time, so we're done with this level already
// (iterator.nextLevel() is called again at the bottom of this outer merge loop)
WikiIterator_nextLevel(&iterator);
}
else
{
WikiIterator_begin(&iterator);
while (!WikiIterator_finished(&iterator))
{
Range A = WikiIterator_nextRange(&iterator);
Range B = WikiIterator_nextRange(&iterator);
if (compare(&array[size * (B.end - 1)], &array[size * A.start]) < 0)
{
// the two ranges are in reverse order, so a simple rotation should fix it
Rotate(array, size, Range_length(A), Range_new(A.start, B.end), cache, cache_size);
}
else if (compare(&array[size * B.start], &array[size * (A.end - 1)]) < 0)
{
// these two ranges weren't already in order, so we'll need to merge them!
memcpy(&cache[0], &array[size * A.start], Range_length(A) * size);
MergeExternal(array, size, A, B, compare, cache);
}
}
}
}
else
{
// this is where the in-place merge logic starts!
// 1. pull out two internal buffers each containing √A unique values
// 1a. adjust block_size and buffer_size if we couldn't find enough unique values
// 2. loop over the A and B subarrays within this level of the merge sort
// 3. break A and B into blocks of len 'block_size'
// 4. "tag" each of the A blocks with values from the first internal buffer
// 5. roll the A blocks through the B blocks and drop/rotate them where they belong
// 6. merge each A block with any B values that follow, using the cache or the second internal buffer
// 7. sort the second internal buffer if it exists
// 8. redistribute the two internal buffers back into the array
size_t block_size = sqrt(WikiIterator_length(&iterator));
size_t buffer_size = WikiIterator_length(&iterator) / block_size + 1;
// as an optimization, we really only need to pull out the internal buffers once for each level of merges
// after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level
Range buffer1, buffer2, A, B;
bool find_separately;
size_t index, last, count, find, start, pull_index = 0;
struct
{
size_t from, to, count;
Range range;
} pull[2];
pull[0].from = pull[0].to = pull[0].count = 0;
pull[0].range = Range_new(0, 0);
pull[1].from = pull[1].to = pull[1].count = 0;
pull[1].range = Range_new(0, 0);
buffer1 = Range_new(0, 0);
buffer2 = Range_new(0, 0);
// find two internal buffers of len 'buffer_size' each
find = buffer_size + buffer_size;
find_separately = false;
if (block_size <= cache_size)
{
// if every A block fits into the cache then we won't need the second internal buffer,
// so we really only need to find 'buffer_size' unique values
find = buffer_size;
}
else if (find > WikiIterator_length(&iterator))
{
// we can't fit both buffers into the same A or B subarray, so find two buffers separately
find = buffer_size;
find_separately = true;
}
// we need to find either a single contiguous space containing 2√A unique values (which will be split up into two buffers of len √A each),
// or we need to find one buffer of < 2√A unique values, and a second buffer of √A unique values,
// OR if we couldn't find that many unique values, we need the largest possible buffer we can get
// in the case where it couldn't find a single buffer of at least √A unique values,
// all of the Merge steps must be replaced by a different merge algorithm (MergeInPlace)
WikiIterator_begin(&iterator);
while (!WikiIterator_finished(&iterator))
{
A = WikiIterator_nextRange(&iterator);
B = WikiIterator_nextRange(&iterator);
// just store information about where the values will be pulled from and to,
// as well as how many values there are, to create the two internal buffers
#define PULL(_to) \
pull[pull_index].range = Range_new(A.start, B.end); \
pull[pull_index].count = count; \
pull[pull_index].from = index; \
pull[pull_index].to = _to
// check A for the number of unique values we need to fill an internal buffer
// these values will be pulled out to the start of A
for (last = A.start, count = 1; count < find; last = index, count++)
{
index = FindLastForward(array, &array[size * last], size, Range_new(last + 1, A.end), compare, find - count);
if (index == A.end)
{