-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort.h
942 lines (831 loc) · 26.6 KB
/
sort.h
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
#pragma once
/**
* Sorting_Algorithm_v1.h
* @author: Kevin German
**/
#include <future>
#include <random>
#include <vector>
#include <algorithm>
namespace sort
{
/**
* @brief available sorting algorithms
**/
enum class SortingAlgorithm
{
none,
cyclesort,
bubblesort,
bubblesortrc,
stdsort,
shellsort,
combsort,
gnomesort,
gnomesort2,
radixsort,
radixsortslow,
radixsortipis,
bogosort,
bozosort,
selectionsort,
insertionsort,
insertionsortbinsearch,
oddevensort,
shakersort,
quicksort,
mergesort,
heapsort,
introsort,
stdstablesort
};
/**
* @brief check container is sorted
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return true if container is sorted, else false
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
bool verifiy_sort_order(I begin, I end, U cmp = U())
{
if (begin == end)
return true;
for (I last = begin++; begin != end; ++begin, ++last)
if (cmp(*begin, *last))
return false;
return true;
}
/**
* @brief check container is sorted recursively
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return true if container is sorted, else false
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
bool verifiy_sort_order_rc(I begin, I end, U cmp = U())
{
I last = begin;
if (begin == end || ++begin == end) //tail call
return true;
if (cmp(*last, *begin))
return verifiy_sort_order_rc(begin, end, cmp);
return false;
}
/**
* @brief inverse order of container
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @return void
**/
template <typename I>
void inverse_order(I begin, I end)
{
using std::swap;
for (; begin != end && begin != --end; ++begin)
swap(*begin, *end);
}
/**
* @brief binary search template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param value: searched value
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return true if value was found, else false
**/
template <typename I, typename V = typename std::iterator_traits<I>::value_type , typename U = std::less<typename std::iterator_traits<I>::value_type> >
bool binary_search(I begin, I end, V &value, U cmp = U())
{
begin = std::lower_bound(begin, end, value, cmp);
return (begin != end && *begin == value);
}
/**
* @brief bubblesort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void bubblesort(I begin, I end, U cmp = U())
{
using std::swap;
for (auto swapped = true; swapped && (begin != end); --end)
{
swapped = false;
for (I i = begin, next = std::next(begin); next != end; ++i, ++next)
{
if (cmp(*next, *i))
{
swap(*i, *next);
swapped = true;
}
}
}
}
template <typename I, typename U>
bool _bubblesort_rc(const I firstBegin, const I begin, I end, U cmp)
{
using std::swap;
if (begin == end)
return true;
const I next = std::next(begin);
if (next == end) //tail call
return true;
auto sorted = true;
if (cmp(*next, *begin)) //sort 2 elements
{
swap(*begin, *next);
sorted = false;
}
sorted &= _bubblesort_rc(firstBegin, std::next(begin), end, cmp);
//1 rc bubblesort run to the last element, will return false if 1 element is not sorted
if (begin == firstBegin && !sorted)
//if first call and array is not sorted, repeat process, but ignore last element
_bubblesort_rc(firstBegin, firstBegin, --end, cmp);
return sorted;
}
/**
* @brief recursive bubblesort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void bubblesort_rc(I begin, I end, U cmp = U())
{
_bubblesort_rc(begin, begin, end, cmp);
}
/**
* @brief combsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void combsort(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
auto sorted = false;
const int length = std::distance(begin, end);
auto gap = length;
while (!sorted)
{
if (gap > 1)
{
sorted = false;
gap = (gap * 10) / 13;
}
else
{
gap = 1;
sorted = true;
}
auto u = 0;
for (I i = begin; u < length - gap; ++i, ++u)
{
I next = std::next(i, gap);
if (cmp(*next, *i))
{
swap(*i, *next);
sorted = false;
}
}
}
}
/**
* @brief shakersort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void shakersort(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
--end;
while (std::distance(begin, end) > 0)
{
for (I i = begin, next = std::next(begin); i != end; ++i, ++next) //from left to right
if (cmp(*next, *i))
swap(*i, *next);
--end;
for (I i = end, prev = end; i != begin; --i) //from right to left
if (cmp(*i, *(--prev)))
swap(*prev, *i);
++begin;
}
}
/**
* @brief insertionsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void insertionsort(I begin, I end, U cmp = U())
{
if (begin == end)
return;
for (I next = std::next(begin), prev; next != end; ++next)
{
auto value = *next;
auto itToBegin = false;
for (prev = std::prev(next); cmp(value, *prev); --prev)
{
*std::next(prev) = std::move(*prev);
if (prev == begin)
{
itToBegin = true;
break;
}
}
if (!itToBegin)
++prev;
*prev = value;
}
}
/**
* @brief insertionsort with binary search template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::remove_reference<decltype(*std::declval<I>())>::type> > //this works for stl but not std::less<decltype(*std::declval<I>())> > -_-
void insertionsort_binsearch(I begin, I end, U cmp = U())
{
//shorter and much nicer version of insertionsort but this is not my work (cppreference) :(
//uses binary search
for (I next = std::next(begin); next != end; ++next)
std::rotate(std::upper_bound(begin, next, *next,cmp), next, std::next(next));
}
/**
* @brief shellsort
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void shellsort(I begin, I end, U cmp = U())
{
const int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; //gapsequence -> A102549 Ciuras sequence
const int num_of_gaps = sizeof(gaps) / sizeof(gaps[0]);
const auto size = std::distance(begin, end);
for (auto g = 0; g < num_of_gaps; ++g) //go through all gaps
{
//insertionsort with gap as distance instead of 1
for (auto gap = gaps[g], j = gap; j < size; j += gap)
{
auto next_Element = std::move(*std::next(begin, j));
auto i = j - gap;
while (i >= 0 && cmp(next_Element, *std::next(begin, i)))
{
*std::next(begin, i + gap) = std::move(*std::next(begin, i));
i -= gap;
}
*std::next(begin, i + gap) = next_Element;
}
}
}
/**
* @brief selectionsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void selectionsort(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
for (; begin != end; ++begin)
{
I min = begin;
for (I next = std::next(begin); next != end; ++next)
if (cmp(*next, *min))
min = next;
swap(*begin, *min);
}
}
/**
* @brief odd-even-sort template (parallel)
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void odd_even_sort(I begin, I end, U cmp = U())
{
using std::swap;
const int dist = std::distance(begin, end);
if (dist <= 1)
return;
bool isOdd = dist % 2;
auto evenSortedCtr = 4, oddSortedCtr = 4;
auto sorted = false;
auto partSort = [&](bool isEvenSort, int *sortedCtr)
{
auto fixedEnd = std::prev(end, isEvenSort ? isOdd : !isOdd);
auto fixedBegin = std::next(begin, isEvenSort ? 0 : 1);
for (auto partSorted = true; !sorted; partSorted = true)
{
for (I i = fixedBegin; i != fixedEnd; i += 2)
{
if (cmp(*std::next(i), *i))
{
swap(*i, *std::next(i));
*sortedCtr = 4;
partSorted = false;
}
}
if (partSorted)
--*sortedCtr;
}
};
std::future<void> feven = std::async(partSort, true, &evenSortedCtr);
std::future<void> fodd = std::async(partSort, false, &oddSortedCtr);
while(oddSortedCtr > 0 || evenSortedCtr > 0)
{
auto status = feven.wait_for(std::chrono::nanoseconds(1000));
if (status == std::future_status::ready)
break;
status = fodd.wait_for(std::chrono::nanoseconds(1000));
if (status == std::future_status::ready)
break;
}
sorted = true;
feven.get();
fodd.get();
}
/**
* @brief cyclesort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void cyclesort(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
I new_pos = std::next(begin);
for (I start = begin; start != end; ++start)
{
I old_pos = start;
auto current_element = *start;
while (start != new_pos) //complete a full cycle
{
new_pos = start;
for (I j = std::next(start); j != end; ++j) //calculate correct position
if (cmp(*j, current_element))
++new_pos;
if (new_pos == old_pos) //check if element is already in correct position
break;
while (!cmp(*new_pos, current_element) && !cmp(current_element, *new_pos)) //position right after duplicates
++new_pos;
old_pos = new_pos;
swap(*new_pos, current_element); //swap to correct position, use now old element in array for comparison
}
}
}
/**
* @brief gnomesort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void gnomesort(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
const I start = begin;
while (begin != std::prev(end))
{
if (cmp(*std::next(begin), *begin))
{
swap(*begin, *std::next(begin));
start != begin ? --begin : ++begin;
}
else
{
++begin;
}
}
}
/**
* @brief gnomesort template with jump to last corrrect position (Insertionsort variation)
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void gnomesort2(I begin, I end, U cmp = U())
{
using std::swap;
if (begin == end)
return;
const I start = begin;
I last = start; //this gnomesort will return to the last position
while (begin != std::prev(end))
{
if (cmp(*std::next(begin), *begin))
{
swap(*begin, *std::next(begin));
start != begin ? --begin : ++begin;
}
else
{
last = begin = std::next(last);
}
}
}
/**
* @brief bogosort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void bogosort(I begin, I end, U cmp = U())
{
using std::swap;
std::random_device seed;
std::mt19937 gen(seed());
std::uniform_int_distribution<int> dist(0, std::distance(begin, end) - 1);
while (!verifiy_sort_order(begin, end, cmp))
for (I i = begin; i != end; ++i)
swap(*i, *std::next(begin, dist(gen)));
}
/**
* @brief bozosort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void bozosort(I begin, I end, U cmp = U())
{
using std::swap;
std::random_device seed;
std::mt19937 gen(seed());
std::uniform_int_distribution<int> dist(0, std::distance(begin, end) - 1);
while (!verifiy_sort_order(begin, end, cmp))
swap(*std::next(begin, dist(gen)), *std::next(begin, dist(gen)));
}
/**
* @brief radixsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param bits: (optional) number of bits used for sorting. default: 32
* @return void
* @note bitwise '&' operator needs to be defined
**/
template <typename I>
void radixsort(I begin, I end,const int bits = 32)
{
std::vector<typename std::iterator_traits<I>::value_type> buckets[2];
const size_t size = std::distance(begin, end);
buckets[0].resize(size);
buckets[1].resize(size);
int top[2] = {0, 0}; //index of next top element in bucket0 and bucket1
for (auto b = 0; b < bits; ++b)
{
for (auto i = begin; i != end; ++i) //sort into buckets
{
if (*i & (1 << b))
buckets[1][top[1]++] = std::move(*i); //next MSB is 1
else
buckets[0][top[0]++] = std::move(*i); //next MSB is 0
}
auto j = begin;
for (auto x = 0; x < top[0]; ++x, ++j)
*j = std::move(buckets[0][x]);
for (auto x = 0; x < top[1]; ++x, ++j)
*j = std::move(buckets[1][x]);
top[0] = top[1] = 0;
}
}
/**
* @brief radixsort template without move operations (expensive copies are used) this
* visualizes the sorting process better and illustrates the performance difference between copy & move
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param bits: (optional) number of bits used for sorting. default: 32
* @return void
* @note bitwise '&' operator needs to be defined
**/
template <typename I>
void radixsort_slow(I begin, I end,const int bits = 32)
{
std::vector<typename std::iterator_traits<I>::value_type> buckets[2];
const size_t size = std::distance(begin, end);
buckets[0].resize(size);
buckets[1].resize(size);
int top[2] = { 0, 0 }; //index of next top element in bucket0 and bucket1
for (auto b = 0; b < bits; ++b)
{
for (auto i = begin; i != end; ++i) //sort into buckets
{
if (*i & (1 << b))
buckets[1][top[1]++] = *i; //next MSB is 1
else
buckets[0][top[0]++] = *i; //next MSB is 0
}
auto j = begin;
for (auto x = 0; x < top[0]; ++x, ++j)
*j = buckets[0][x];
for (auto x = 0; x < top[1]; ++x, ++j)
*j = buckets[1][x];
top[0] = top[1] = 0;
}
}
/**
* @brief radixsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param bits: (optional) number of bits used for sorting. default: 32
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @param maxThreads: (optional) max. number of threads which can run this algorithm parallel. default: 0
* @return void
* @note bitwise '&' operator needs to be defined
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void radixsort_ip_is(I begin, I end,int bits = 32, U cmp = U(), int maxThreads = 0)
{
using std::swap;
if (std::distance(begin, end) <= 1)
return;
--bits;
auto lb = begin; //left index
auto rb = std::prev(end); //right index
while (lb != rb)
{
if (*lb & (1 << bits)) //move all 1's to the right and 0's to the left
{
swap(*lb, *rb);
--rb; //rb moves to next element, because digit of current element is definitly '1'
}
else
{
++lb; //digit of current element is 0, move to next element with lb
}
}
if (*lb & (1 << bits) && lb != begin) //lb needs to be placed on the last 0, for splitting the array
--lb;
if (bits != 0)
{
if (std::distance(begin, end) < 20) //switch to insertionsort if size gets smaller than 20
{
insertionsort(begin, std::next(lb),cmp);
insertionsort(std::next(lb), end,cmp);
}
else
{
std::future<void> f1, f2;
//rec. call on array with leading 0's of current call
if (lb != begin)
{
if (maxThreads > 0)
f1 = std::async([&]() { radixsort_ip_is(begin, std::next(lb), bits, cmp,--maxThreads); });
else
radixsort_ip_is(begin, std::next(lb), bits, cmp, 0);
}
//rec. call array with leading 1's
if (rb != std::prev(end))
{
if (maxThreads > 0)
f2 = std::async([&]() { radixsort_ip_is(std::next(lb), end, bits, cmp, --maxThreads); });
else
radixsort_ip_is(std::next(lb), end, bits, cmp, 0);
}
//wait for finish if started
if (f1.valid())
f1.get();
if (f2.valid())
f2.get();
}
}
}
/**
* @brief partition template. Moves all elements smaller than the pivot to the left and everything else to the right
* @param begin: iterator to the begin of the container
* @param pivot: iterator to the end of the container which contains the pivot element
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return Iterator to the correct position of the pivot element
**/
template <typename I, typename U>
I partition(I begin, I pivot, U cmp)
{
using std::swap;
I pivPos = begin;
while (begin != pivot)
{
if (cmp(*begin, *pivot))
{
swap(*begin, *pivPos);
++pivPos;
}
++begin;
}
//last position of element which is not < as the pivot
return pivPos;
}
/**
* @brief median of three template. returns the b for a < b < c
* @param first: iterator to the first element
* @param second: iterator to the second element
* @param third: iterator to the third element
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return iterator reference tob for a < b < c
**/
template <typename I, typename U = std::less <typename std::iterator_traits<I>::value_type> >
I median_of_three(const I &first,const I &second,const I &third, U cmp = U())
{
return std::max(std::min(first, second,cmp), std::min(std::max(first, second, cmp), third, cmp), cmp);
}
/**
* @brief quicksort template (with optional multithreading)
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @param maxThreads: number of max concurrent threads. default = 0 (no multithreading)
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void quicksort(I begin, I end, U cmp = U(), const int maxThreads = 0)
{
using std::swap;
const auto dist = std::distance(begin, end);
if (dist < 2) //tail call
return;
//median of three
I pivot = std::prev(end);
swap(*median_of_three(begin, std::next(begin, dist / 2), std::prev(end), cmp), *pivot);
//partition
I pivPos = sort::partition(begin, pivot, cmp);
//move pivot to correct position
swap(*pivPos, *pivot);
if (maxThreads > 1)
{
std::future<void> f1 = std::async([&]() {quicksort(begin, pivPos, cmp, maxThreads - 2); });
std::future<void> f2 = std::async([&]() {quicksort(std::next(pivPos), end, cmp, maxThreads - 2); });
f1.get();
f2.get();
}
else
{
quicksort(begin, pivPos, cmp,0);
quicksort(std::next(pivPos), end, cmp,0);
}
}
/**
* @brief heapsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void heapsort(I begin, I end, U cmp = U())
{
std::make_heap(begin, end, cmp);
std::sort_heap(begin, end, cmp);
}
/**
* @brief in place merge template which degrades the runtime of mergesort because of my poor implementation
* (std::inplace_merge(begin, mid,end) is much better)
* @param begin: iterator to the begin of the container
* @param mid: iterator to the mid of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type>>
void inplace_merge(I begin, I mid, I end, U cmp = U())
{
I &leftList = begin;
I &rightList = mid;
while (leftList != mid && rightList != end)
{
if (cmp(*rightList,*leftList))
{
auto tmp = std::move(*leftList);
*leftList = std::move(*rightList);
//move all elements to the left, until correct position is found
auto i = std::next(rightList);
for(;i != end && cmp(*i,tmp);++i)
{
*std::prev(i) = std::move(*i);
}
//place the old value from left list in correct position of rightlist
*--i = std::move(tmp);
}
else
{
++leftList;
}
}
}
/**
* @brief mergesort template (optional multithreading)
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @param maxThreads: number of max concurrent threads. default = 0 (no multithreading)
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> > //this works but not std::less<decltype(*std::declval<I>())> > -_-
void mergesort(I begin, I end, U cmp = U(), int maxThreads = 0)
{
const auto dist = std::distance(begin, end);
//tail call
if (dist < 2)
return;
//split
I mid = std::next(begin, dist / 2);
if (maxThreads > 1)
{
std::future<void> f1 = std::async([&]() {mergesort(begin, mid,cmp, maxThreads - 2); });
std::future<void> f2 = std::async([&]() {mergesort(mid, end, cmp, maxThreads - 2); });
f1.get();
f2.get();
}
else
{
mergesort(begin, mid, cmp,0);
mergesort(mid, end, cmp,0);
}
//merge
std::inplace_merge(begin, mid,end,cmp);
//inplace_merge(begin,mid,end,cmp); //slow, because of the shifts required
}
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type>>
void _introsort(I begin, I end, U cmp = U(),const int maxDepth = 8,const int maxThreads = 0)
{
using std::swap;
const auto dist = std::distance(begin, end);
if (dist < 2) //tail call
return;
if (maxDepth == 0)
{
heapsort(begin, end, cmp);
return;
}
//median of three
I pivot = std::prev(end);
swap(*median_of_three(begin, std::next(begin, dist / 2), std::prev(end), cmp), *pivot);
//partition
I pivPos = sort::partition(begin, pivot, cmp);
//move pivot to correct position
swap(*pivPos, *pivot);
if (maxThreads > 1)
{
std::future<void> f1 = std::async([&]() {_introsort(begin, pivPos, cmp, maxDepth - 1,maxThreads - 2); });
std::future<void> f2 = std::async([&]() {_introsort(std::next(pivPos), end, cmp, maxDepth - 1,maxThreads - 2); });
f1.get();
f2.get();
}
else
{
_introsort(begin, pivPos, cmp, maxDepth - 1, 0);
_introsort(std::next(pivPos), end, cmp, maxDepth - 1, 0);
}
}
/**
* @brief introsort template
* @param begin: iterator to the begin of the container
* @param end: iterator to the end of the container
* @param cmp: (optional) compare function (bool cmp(const X &a,const X &b);) which returns true if a < b.
* @param maxThreads: (optional) max. number of threads which can run this algorithm parallel. default: 0
* @return void
**/
template <typename I, typename U = std::less<typename std::iterator_traits<I>::value_type> >
void introsort(I begin, I end, U cmp = U(),int maxThreads = 0)
{
const auto dist = std::distance(begin, end);
const auto maxDepth = static_cast<int>(std::log2(static_cast<double>(dist)));
_introsort(begin, end, cmp, maxDepth,maxThreads);
}
}