-
Notifications
You must be signed in to change notification settings - Fork 7
/
sort.h
2032 lines (1709 loc) · 74.4 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
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
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// This file implements sorting algorithms. Some of these are equivalent to
// std C++ sorting algorithms, while others don't have equivalents in the
// C++ standard. We implement the following sorting algorithms:
// isSorted --
// sort -- Unstable. The implementation of this is mapped to quickSort by default.
// quickSort -- Unstable. This is actually an intro-sort (quick sort with switch to insertion sort).
// tim_sort -- Stable.
// tim_sort_buffer -- Stable.
// partialSort -- Unstable.
// insertionSort -- Stable.
// shellSort -- Unstable.
// heapSort -- Unstable.
// stableSort -- Stable. The implementation of this is simply mapped to mergeSort.
// merge --
// mergeSort -- Stable.
// mergeSortBuffer -- Stable.
// nthElement -- Unstable.
// radixSort -- Stable. Important and useful sort for integral data, and faster than all others for this.
// combSort -- Unstable. Possibly the best combination of small code size but fast sort.
// bubbleSort -- Stable. Useful in practice for sorting tiny sets of data (<= 10 elements).
// selectionSort* -- Unstable.
// shakerSort* -- Stable.
// bucketSort* -- Stable.
//
// * Found in sort_extra.h.
//
// Additional sorting and related algorithms we may want to implement:
// partialSort_copy This would be like the std STL version.
// paritition This would be like the std STL version. This is not categorized as a sort routine by the language standard.
// stable_partition This would be like the std STL version.
// counting_sort Maybe we don't want to implement this.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_SORT_H
#define EASTL_SORT_H
#include <eastl/internal/config.h>
#include <eastl/internal/move_help.h>
#include <eastl/iterator.h>
#include <eastl/memory.h>
#include <eastl/algorithm.h>
#include <eastl/functional.h>
#include <eastl/heap.h>
#include <eastl/allocator.h>
#include <eastl/memory.h>
#if defined(EASTL_PRAGMA_ONCE_SUPPORTED)
#pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result.
#endif
// EASTL_PLATFORM_PREFERRED_ALIGNMENT
//
// Allows for slightly faster buffers in some cases.
//
#if !defined(EASTL_PLATFORM_PREFERRED_ALIGNMENT)
#if defined(EA_PROCESSOR_ARM)
#define EASTL_PLATFORM_PREFERRED_ALIGNMENT 8
#else
#define EASTL_PLATFORM_PREFERRED_ALIGNMENT 16
#endif
#endif
namespace eastl
{
/// isSorted
///
/// Returns true if the range [first, last) is sorted.
/// An empty range is considered to be sorted.
/// To test if a range is reverse-sorted, use 'greater' as the comparison
/// instead of 'less'.
///
/// Example usage:
/// vector<int> intArray;
/// bool bIsSorted = isSorted(intArray.begin(), intArray.end());
/// bool bIsReverseSorted = isSorted(intArray.begin(), intArray.end(), greater<int>());
///
template <typename ForwardIterator, typename StrictWeakOrdering>
bool isSorted(ForwardIterator first, ForwardIterator last, StrictWeakOrdering compare)
{
if(first != last)
{
ForwardIterator current = first;
for(++current; current != last; first = current, ++current)
{
if(compare(*current, *first))
{
EASTL_VALIDATE_COMPARE(!compare(*first, *current)); // Validate that the compare function is sane.
return false;
}
}
}
return true;
}
template <typename ForwardIterator>
inline bool isSorted(ForwardIterator first, ForwardIterator last)
{
typedef eastl::less<typename eastl::iterator_traits<ForwardIterator>::value_type> Less;
return eastl::isSorted<ForwardIterator, Less>(first, last, Less());
}
/// isSorted_until
///
/// Returns an iterator to the first element in the range [first,last) which does not follow an ascending order.
/// The range between first and the iterator returned is sorted.
/// If the entire range is sorted, the function returns last.
/// The elements are compared using operator< for the first version, and comp for the second.
///
/// Example usage:
/// vector<int> intArray;
/// vector<int>::iterator unsorted_element = isSorted_until(eastl::end(intArray), eastl::end(intArray));
/// vector<int>::iterator unsorted_element_with_user_compare = isSorted_until(eastl::end(intArray), eastl::end(intArray), eastl::less<int>());
///
template<typename ForwardIterator>
ForwardIterator isSorted_until(ForwardIterator first, ForwardIterator last)
{
if(first != last)
{
ForwardIterator next = first;
while(++next != last)
{
if(*next < *first)
return next;
first = next;
}
}
return last;
}
template<typename ForwardIterator, typename Compare>
ForwardIterator isSorted_until(ForwardIterator first, ForwardIterator last, Compare compare)
{
if(first != last)
{
ForwardIterator next = first;
while(++next != last)
{
if(compare(*next, *first))
return next;
first = next;
}
}
return last;
}
/// merge
///
/// This function merges two sorted input sorted ranges into a result sorted range.
/// This merge is stable in that no element from the first range will be changed
/// in order relative to other elements from the first range.
///
template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Compare>
OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare)
{
while((first1 != last1) && (first2 != last2))
{
if(compare(*first2, *first1))
{
EASTL_VALIDATE_COMPARE(!compare(*first1, *first2)); // Validate that the compare function is sane.
*result = *first2;
++first2;
}
else
{
*result = *first1;
++first1;
}
++result;
}
// Check which list is empty and explicitly copy remaining items from the other list.
// For performance reasons, only a single copy operation is invoked to avoid the potential overhead
// introduced by chaining two copy operations together. Even if a copy is of zero size there can
// be overhead from calling memmove with a zero size copy.
if (first1 == last1)
{
return eastl::copy(first2, last2, result);
}
else
{
return eastl::copy(first1, last1, result);
}
}
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
inline OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
{
typedef eastl::less<typename eastl::iterator_traits<InputIterator1>::value_type> Less;
return eastl::merge<InputIterator1, InputIterator2, OutputIterator, Less>
(first1, last1, first2, last2, result, Less());
}
//////////////////////////////////////////////////////////////////////////////
/// insertionSort
///
/// insertionSort is an O(n^2) stable sorting algorithm that starts at the
/// (k + 1) element and assumes the first (k) elements are sorted.
/// Then copyBackwards from (k + 1) to the begining any elements where the
/// (k + 1) element is less than [0, k] elements. The position of k when
/// (k + 1) element is not less than k is the sorted position of the (k + 1) element.
///
/// Example With Intermediate Steps:
/// (k + 1) == 2 : [3, 2, 1] -> [3, 3, 1] -> [2, 3, 1]
/// (k + 1) == 1 : [2, 3, 1] -> [2, 3, 3] -> [2, 2, 3] -> [1, 2, 3]
/// : [1, 2, 3]
template <typename BidirectionalIterator, typename StrictWeakOrdering>
void insertionSort(BidirectionalIterator first, BidirectionalIterator last, StrictWeakOrdering compare)
{
typedef typename eastl::iterator_traits<BidirectionalIterator>::value_type value_type;
if (first != last)
{
BidirectionalIterator i = first;
for (++i; i != last; ++i)
{
value_type insertValue(eastl::move(*i));
BidirectionalIterator insertPosition = i;
for (BidirectionalIterator movePosition = i; movePosition != first && compare(insertValue, *(--movePosition)); --insertPosition)
{
EASTL_VALIDATE_COMPARE(!compare(*movePosition, insertValue));
*insertPosition = eastl::move(*movePosition);
}
*insertPosition = eastl::move(insertValue);
}
}
} // insertionSort
template <typename BidirectionalIterator>
void insertionSort(BidirectionalIterator first, BidirectionalIterator last)
{
typedef eastl::less<typename eastl::iterator_traits<BidirectionalIterator>::value_type> Less;
insertionSort<BidirectionalIterator>(first, last, Less());
} // insertionSort
/// shellSort
///
/// Implements the ShellSort algorithm. This algorithm is a serious algorithm for larger
/// data sets, as reported by Sedgewick in his discussions on QuickSort. Note that shellSort
/// requires a random access iterator, which usually means an array (eg. vector, deque).
/// ShellSort has good performance with presorted sequences.
/// The term "shell" derives from the name of the inventor, David Shell.
///
/// To consider: Allow the user to specify the "h-sequence" array.
///
template <typename RandomAccessIterator, typename StrictWeakOrdering>
void shellSort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering compare)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type;
// We use the Knuth 'h' sequence below, as it is easy to calculate at runtime.
// However, possibly we are better off using a different sequence based on a table.
// One such sequence which averages slightly better than Knuth is:
// 1, 5, 19, 41, 109, 209, 505, 929, 2161, 3905, 8929, 16001, 36289,
// 64769, 146305, 260609, 587521, 1045505, 2354689, 4188161, 9427969, 16764929
if(first != last)
{
const difference_type nSize = last - first;
difference_type nSpace = 1; // nSpace is the 'h' value of the ShellSort algorithm.
while(nSpace < nSize)
nSpace = (nSpace * 3) + 1; // This is the Knuth 'h' sequence: 1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, 2391484, 7174453, 21523360, 64570081, 193710244,
for(nSpace = (nSpace - 1) / 3; nSpace >= 1; nSpace = (nSpace - 1) / 3) // Integer division is less than ideal.
{
for(difference_type i = 0; i < nSpace; i++)
{
const RandomAccessIterator iInsertFirst = first + i;
// Note: we can only move the iterator forward if we know we won't overrun the
// end(), otherwise we can invoke undefined behaviour. So we need to check we
// have enough space before moving the iterator.
RandomAccessIterator iSorted = iInsertFirst;
while(distance(iSorted, last) > nSpace)
{
iSorted += nSpace;
RandomAccessIterator iCurrent = iSorted;
for(RandomAccessIterator iBack = iSorted - nSpace; (iCurrent != iInsertFirst) && compare(*iCurrent, *iBack); iCurrent = iBack, iBack -= nSpace)
{
EASTL_VALIDATE_COMPARE(!compare(*iBack, *iCurrent)); // Validate that the compare function is sane.
eastl::iterSwap(iCurrent, iBack);
}
}
}
}
}
} // shellSort
template <typename RandomAccessIterator>
inline void shellSort(RandomAccessIterator first, RandomAccessIterator last)
{
typedef eastl::less<typename eastl::iterator_traits<RandomAccessIterator>::value_type> Less;
eastl::shellSort<RandomAccessIterator, Less>(first, last, Less());
}
/// heapSort
///
/// Implements the HeapSort algorithm.
/// Note that heapSort requires a random access iterator, which usually means
/// an array (eg. vector, deque).
///
template <typename RandomAccessIterator, typename StrictWeakOrdering>
void heapSort(RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering compare)
{
// We simply call our heap algorithms to do the work for us.
eastl::makeHeap<RandomAccessIterator, StrictWeakOrdering>(first, last, compare);
eastl::sortHeap<RandomAccessIterator, StrictWeakOrdering>(first, last, compare);
}
template <typename RandomAccessIterator>
inline void heapSort(RandomAccessIterator first, RandomAccessIterator last)
{
typedef eastl::less<typename eastl::iterator_traits<RandomAccessIterator>::value_type> Less;
eastl::heapSort<RandomAccessIterator, Less>(first, last, Less());
}
namespace Internal
{
// Sorts a range whose initial (start - first) entries are already sorted.
// This function is a useful helper to the tim_sort function.
// This is the same as insertionSort except that it has a start parameter which indicates
// where the start of the unsorted data is.
template <typename BidirectionalIterator, typename StrictWeakOrdering>
void insertionSort_already_started(BidirectionalIterator first, BidirectionalIterator last, BidirectionalIterator start, StrictWeakOrdering compare)
{
typedef typename eastl::iterator_traits<BidirectionalIterator>::value_type value_type;
if (first != last) // if the range is non-empty...
{
BidirectionalIterator iCurrent, iNext, iSorted = start - 1;
for (++iSorted; iSorted != last; ++iSorted)
{
const value_type temp(*iSorted);
iNext = iCurrent = iSorted;
for (--iCurrent; (iNext != first) && compare(temp, *iCurrent); --iNext, --iCurrent)
{
EASTL_VALIDATE_COMPARE(!compare(*iCurrent, temp)); // Validate that the compare function is sane.
*iNext = *iCurrent;
}
*iNext = temp;
}
}
}
}
/// mergeSortBuffer
///
/// Implements the MergeSort algorithm with a user-supplied buffer.
/// The input buffer must be able to hold a number of items equal to 'last - first'.
/// Note that mergeSortBuffer requires a random access iterator, which usually means
/// an array (eg. vector, deque).
///
/// The algorithm used for merge sort is not the standard merge sort. It has been modified
/// to improve performance for data that is already partially sorted. In fact, if data
/// is completely sorted, then performance is O(n), but even data with partially sorted
/// regions can benefit from the modifications.
///
/// 'InsertionSortLimit' specifies a size limit for which the algorithm will use insertion sort.
/// Due to the overhead of merge sort, it is often faster to use insertion sort once the size of a region
/// is fairly small. However, insertion sort is not as efficient (in terms of assignments orcomparisons)
/// so choosing a value that is too large will reduce performance. Generally a value of 16 to 32 is reasonable,
/// but the best choose will depend on the data being sorted.
template <typename RandomAccessIterator, typename T, typename StrictWeakOrdering, typename difference_type, int InsertionSortLimit>
class MergeSorter
{
public:
static void sort(RandomAccessIterator first, RandomAccessIterator last, T* pBuffer, StrictWeakOrdering compare)
{
if (sort_impl(first, last, pBuffer, difference_type(0), compare) == RL_Buffer)
{
const difference_type nCount = last - first;
eastl::copy<T*, RandomAccessIterator>(pBuffer, pBuffer + nCount, first);
}
EASTL_DEV_ASSERT((eastl::isSorted<RandomAccessIterator, StrictWeakOrdering>(first, last, compare)));
}
private:
static_assert(InsertionSortLimit > 1, "Sequences of length 1 are already sorted. Use a larger value for InsertionSortLimit");
enum ResultLocation
{
RL_SourceRange, // i.e. result is in the range defined by [first, last)
RL_Buffer, // i.e. result is in pBuffer
};
// sort_impl
//
// This sort routine sorts the data in [first, last) and places the result in pBuffer or in the original range of the input. The actual
// location of the data is indicated by the enum returned.
//
// lastSortedEnd is used to specify a that data in the range [first, first + lastSortedEnd] is already sorted. This information is used
// to avoid unnecessary merge sorting of already sorted data. lastSortedEnd is a hint, and can be an under estimate of the sorted elements
// (i.e. it is legal to pass 0).
static ResultLocation sort_impl(RandomAccessIterator first, RandomAccessIterator last, T* pBuffer, difference_type lastSortedEnd, StrictWeakOrdering compare)
{
const difference_type nCount = last - first;
if (lastSortedEnd < 1)
{
lastSortedEnd = eastl::isSorted_until<RandomAccessIterator, StrictWeakOrdering>(first, last, compare) - first;
}
// Sort the region unless lastSortedEnd indicates it is already sorted.
if (lastSortedEnd < nCount)
{
// If the size is less than or equal to InsertionSortLimit use insertion sort instead of recursing further.
if (nCount <= InsertionSortLimit)
{
eastl::Internal::insertionSort_already_started<RandomAccessIterator, StrictWeakOrdering>(first, last, first + lastSortedEnd, compare);
return RL_SourceRange;
}
else
{
const difference_type nMid = nCount / 2;
ResultLocation firstHalfLocation = RL_SourceRange;
// Don't sort the first half if it is already sorted.
if (lastSortedEnd < nMid)
{
firstHalfLocation = sort_impl(first, first + nMid, pBuffer, lastSortedEnd, compare);
}
ResultLocation secondHalfLocation = sort_impl(first + nMid, last, pBuffer + nMid, lastSortedEnd - nMid, compare);
return merge_halves(first, last, nMid, pBuffer, firstHalfLocation, secondHalfLocation, compare);
}
}
else
{
EASTL_DEV_ASSERT((eastl::isSorted<RandomAccessIterator, StrictWeakOrdering>(first, last, compare)));
return RL_SourceRange;
}
}
// merge_halves
//
// Merge two sorted regions of elements.
// The inputs to this method effectively define two large buffers. The variables 'firstHalfLocation' and 'secondHalfLocation' define where the data to be
// merged is located within the two buffers. It is entirely possible that the two areas to be merged could be entirely located in either of the larger buffers.
// Upon returning the merged results will be in one of the two buffers (indicated by the return result).
static ResultLocation merge_halves(RandomAccessIterator first, RandomAccessIterator last, difference_type nMid, T* pBuffer, ResultLocation firstHalfLocation, ResultLocation secondHalfLocation, StrictWeakOrdering compare)
{
const difference_type nCount = last - first;
if (firstHalfLocation == RL_SourceRange)
{
if (secondHalfLocation == RL_SourceRange)
{
eastl::merge<RandomAccessIterator, RandomAccessIterator, T*, StrictWeakOrdering>(first, first + nMid, first + nMid, last, pBuffer, compare);
EASTL_DEV_ASSERT((eastl::isSorted<T*, StrictWeakOrdering>(pBuffer, pBuffer + nCount, compare)));
return RL_Buffer;
}
else
{
eastl::copy(first, first + nMid, pBuffer);
eastl::merge<T*, T*, RandomAccessIterator, StrictWeakOrdering>(pBuffer, pBuffer + nMid, pBuffer + nMid, pBuffer + nCount, first, compare);
EASTL_DEV_ASSERT((eastl::isSorted<RandomAccessIterator, StrictWeakOrdering>(first, last, compare)));
return RL_SourceRange;
}
}
else
{
if (secondHalfLocation == RL_SourceRange)
{
eastl::copy(first + nMid, last, pBuffer + nMid);
eastl::merge<T*, T*, RandomAccessIterator, StrictWeakOrdering>(pBuffer, pBuffer + nMid, pBuffer + nMid, pBuffer + nCount, first, compare);
EASTL_DEV_ASSERT((eastl::isSorted<RandomAccessIterator, StrictWeakOrdering>(first, last, compare)));
return RL_SourceRange;
}
else
{
eastl::merge<T*, T*, RandomAccessIterator, StrictWeakOrdering>(pBuffer, pBuffer + nMid, pBuffer + nMid, pBuffer + nCount, first, compare);
EASTL_DEV_ASSERT((eastl::isSorted<RandomAccessIterator, StrictWeakOrdering>(first, last, compare)));
return RL_SourceRange;
}
}
}
};
template <typename RandomAccessIterator, typename T, typename StrictWeakOrdering>
void mergeSortBuffer(RandomAccessIterator first, RandomAccessIterator last, T* pBuffer, StrictWeakOrdering compare)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type;
MergeSorter<RandomAccessIterator, T, StrictWeakOrdering, difference_type, 16>::sort(first, last, pBuffer, compare);
}
template <typename RandomAccessIterator, typename T>
inline void mergeSortBuffer(RandomAccessIterator first, RandomAccessIterator last, T* pBuffer)
{
typedef eastl::less<typename eastl::iterator_traits<RandomAccessIterator>::value_type> Less;
eastl::mergeSortBuffer<RandomAccessIterator, T, Less>(first, last, pBuffer, Less());
}
/// mergeSort
///
/// Implements the MergeSort algorithm.
/// This algorithm allocates memory via the user-supplied allocator. Use mergeSortBuffer
/// function if you want a version which doesn't allocate memory.
/// Note that mergeSort requires a random access iterator, which usually means
/// an array (eg. vector, deque).
///
template <typename RandomAccessIterator, typename Allocator, typename StrictWeakOrdering>
void mergeSort(RandomAccessIterator first, RandomAccessIterator last, Allocator& allocator, StrictWeakOrdering compare)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type;
typedef typename eastl::iterator_traits<RandomAccessIterator>::value_type value_type;
const difference_type nCount = last - first;
if(nCount > 1)
{
// We need to allocate an array of nCount value_type objects as a temporary buffer.
value_type* const pBuffer = (value_type*)allocate_memory(allocator, nCount * sizeof(value_type), EASTL_ALIGN_OF(value_type), 0);
eastl::uninitializedFill(pBuffer, pBuffer + nCount, value_type());
eastl::mergeSortBuffer<RandomAccessIterator, value_type, StrictWeakOrdering>
(first, last, pBuffer, compare);
eastl::destruct(pBuffer, pBuffer + nCount);
EASTLFree(allocator, pBuffer, nCount * sizeof(value_type));
}
}
template <typename RandomAccessIterator, typename Allocator>
inline void mergeSort(RandomAccessIterator first, RandomAccessIterator last, Allocator& allocator)
{
typedef eastl::less<typename eastl::iterator_traits<RandomAccessIterator>::value_type> Less;
eastl::mergeSort<RandomAccessIterator, Allocator, Less>(first, last, allocator, Less());
}
/// partition
///
/// Implements the partition algorithm.
/// Rearranges the elements in the range [first, last), in such a way that all the elements
/// for which pred returns true precede all those for which it returns false. The iterator
/// returned points to the first element of the second group.
/// The relative ordering within each group is not necessarily the same as before the call.
/// See function stable_partition for a function with a similar behavior and stability in
/// the ordering.
///
/// To do: Implement a version that uses a faster BidirectionalIterator algorithm for the
/// case that the iterator range is a bidirectional iterator instead of just an
/// input iterator (one direction).
///
template<typename InputIterator, typename Predicate>
InputIterator partition(InputIterator begin, InputIterator end, Predicate predicate)
{
if(begin != end)
{
while(predicate(*begin))
{
if(++begin == end)
return begin;
}
InputIterator middle = begin;
while(++middle != end)
{
if(predicate(*middle))
{
eastl::swap(*begin, *middle);
++begin;
}
}
}
return begin;
}
/// stable_partition
///
/// Performs the same function as @p partition() with the additional
/// guarantee that the relative ordering of elements in each group is
/// preserved.
template <typename ForwardIterator, typename Predicate>
ForwardIterator stable_partition(ForwardIterator first, ForwardIterator last, Predicate pred)
{
first = eastl::findIf_not(first, last, pred);
if (first == last)
return first;
typedef typename iterator_traits<ForwardIterator>::value_type value_type;
const auto requested_size = eastl::distance(first, last);
auto allocator = *getDefaultAllocator(0);
value_type* const buffer =
(value_type*)allocate_memory(allocator, requested_size * sizeof(value_type), EASTL_ALIGN_OF(value_type), 0);
eastl::uninitializedFill(buffer, buffer + requested_size, value_type());
ForwardIterator result1 = first;
value_type* result2 = buffer;
*result2 = eastl::move(*first);
++result2;
++first;
for (; first != last; ++first)
{
if (pred(*first))
{
*result1 = eastl::move(*first);
++result1;
}
else
{
*result2 = eastl::move(*first);
++result2;
}
}
eastl::copy(buffer, result2, result1);
eastl::destruct(buffer, buffer + requested_size);
EASTLFree(allocator, buffer, requested_size * sizeof(value_type));
return result1;
}
/////////////////////////////////////////////////////////////////////
// quickSort
//
// We do the "introspection sort" variant of quick sort which is now
// well-known and understood. You can read about this algorithm in
// many articles on quick sort, but briefly what it does is a median-
// of-three quick sort whereby the recursion depth is limited to a
// some value (after which it gives up on quick sort and switches to
// a heap sort) and whereby after a certain amount of sorting the
// algorithm stops doing quick-sort and finishes the sorting via
// a simple insertion sort.
/////////////////////////////////////////////////////////////////////
#if (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64))
static const int kQuickSortLimit = 28; // For sorts of random arrays over 100 items, 28 - 32 have been found to be good numbers on x86.
#else
static const int kQuickSortLimit = 16; // It seems that on other processors lower limits are more beneficial, as they result in fewer compares.
#endif
namespace Internal
{
template <typename Size>
inline Size Log2(Size n)
{
int i;
for(i = 0; n; ++i)
n >>= 1;
return i - 1;
}
// To do: Investigate the speed of this bit-trick version of Log2.
// It may work better on some platforms but not others.
//
// union FloatUnion {
// float f;
// uint32_t i;
// };
//
// inline uint32_t Log2(uint32_t x)
// {
// const FloatInt32Union u = { x };
// return (u.i >> 23) - 127;
// }
}
template <typename RandomAccessIterator, typename T>
inline RandomAccessIterator getPartition_impl(RandomAccessIterator first, RandomAccessIterator last, T&& pivotValue)
{
for(; ; ++first)
{
while(*first < pivotValue)
{
EASTL_VALIDATE_COMPARE(!(pivotValue < *first)); // Validate that the compare function is sane.
++first;
}
--last;
while(pivotValue < *last)
{
EASTL_VALIDATE_COMPARE(!(*last < pivotValue)); // Validate that the compare function is sane.
--last;
}
if(first >= last) // Random access iterators allow operator >=
return first;
eastl::iterSwap(first, last);
}
}
/// getPartition
///
/// This function takes const T& instead of T because T may have special alignment
/// requirements and some compilers (e.g. VC++) are don't respect alignment requirements
/// for function arguments.
///
template <typename RandomAccessIterator, typename T>
inline RandomAccessIterator getPartition(RandomAccessIterator first, RandomAccessIterator last, const T& pivotValue)
{
const T pivotCopy(pivotValue); // Need to make a temporary because the sequence below is mutating.
return getPartition_impl<RandomAccessIterator, const T&>(first, last, pivotCopy);
}
template <typename RandomAccessIterator, typename T>
inline RandomAccessIterator getPartition(RandomAccessIterator first, RandomAccessIterator last, T&& pivotValue)
{
// Note: unlike the copy-constructible variant of getPartition... we can't create a temporary const move-constructible object
return getPartition_impl<RandomAccessIterator, T&&>(first, last, eastl::move(pivotValue));
}
template <typename RandomAccessIterator, typename T, typename Compare>
inline RandomAccessIterator getPartition_impl(RandomAccessIterator first, RandomAccessIterator last, T&& pivotValue, Compare compare)
{
for(; ; ++first)
{
while(compare(*first, pivotValue))
{
EASTL_VALIDATE_COMPARE(!compare(pivotValue, *first)); // Validate that the compare function is sane.
++first;
}
--last;
while(compare(pivotValue, *last))
{
EASTL_VALIDATE_COMPARE(!compare(*last, pivotValue)); // Validate that the compare function is sane.
--last;
}
if(first >= last) // Random access iterators allow operator >=
return first;
eastl::iterSwap(first, last);
}
}
template <typename RandomAccessIterator, typename T, typename Compare>
inline RandomAccessIterator getPartition(RandomAccessIterator first, RandomAccessIterator last, const T& pivotValue, Compare compare)
{
const T pivotCopy(pivotValue); // Need to make a temporary because the sequence below is mutating.
return getPartition_impl<RandomAccessIterator, const T&, Compare>(first, last, pivotCopy, compare);
}
template <typename RandomAccessIterator, typename T, typename Compare>
inline RandomAccessIterator getPartition(RandomAccessIterator first, RandomAccessIterator last, T&& pivotValue, Compare compare)
{
// Note: unlike the copy-constructible variant of getPartition... we can't create a temporary const move-constructible object
return getPartition_impl<RandomAccessIterator, T&&, Compare>(first, last, eastl::forward<T>(pivotValue), compare);
}
namespace Internal
{
// This function is used by quickSort and is not intended to be used by itself.
// This is because the implementation below makes an assumption about the input
// data that quickSort satisfies but arbitrary data may not.
// There is a standalone insertionSort function.
template <typename RandomAccessIterator>
inline void insertionSort_simple(RandomAccessIterator first, RandomAccessIterator last)
{
for(RandomAccessIterator current = first; current != last; ++current)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::value_type value_type;
RandomAccessIterator end(current), prev(current);
value_type value(eastl::forward<value_type>(*current));
for(--prev; value < *prev; --end, --prev) // We skip checking for (prev >= first) because quickSort (our caller) makes this unnecessary.
{
EASTL_VALIDATE_COMPARE(!(*prev < value)); // Validate that the compare function is sane.
*end = eastl::forward<value_type>(*prev);
}
*end = eastl::forward<value_type>(value);
}
}
// This function is used by quickSort and is not intended to be used by itself.
// This is because the implementation below makes an assumption about the input
// data that quickSort satisfies but arbitrary data may not.
// There is a standalone insertionSort function.
template <typename RandomAccessIterator, typename Compare>
inline void insertionSort_simple(RandomAccessIterator first, RandomAccessIterator last, Compare compare)
{
for(RandomAccessIterator current = first; current != last; ++current)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::value_type value_type;
RandomAccessIterator end(current), prev(current);
value_type value(eastl::forward<value_type>(*current));
for(--prev; compare(value, *prev); --end, --prev) // We skip checking for (prev >= first) because quickSort (our caller) makes this unnecessary.
{
EASTL_VALIDATE_COMPARE(!compare(*prev, value)); // Validate that the compare function is sane.
*end = eastl::forward<value_type>(*prev);
}
*end = eastl::forward<value_type>(value);
}
}
} // namespace Internal
template <typename RandomAccessIterator>
inline void partialSort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type;
typedef typename eastl::iterator_traits<RandomAccessIterator>::value_type value_type;
eastl::makeHeap<RandomAccessIterator>(first, middle);
for(RandomAccessIterator i = middle; i < last; ++i)
{
if(*i < *first)
{
EASTL_VALIDATE_COMPARE(!(*first < *i)); // Validate that the compare function is sane.
value_type temp(eastl::forward<value_type>(*i));
*i = eastl::forward<value_type>(*first);
eastl::adjustHeap<RandomAccessIterator, difference_type, value_type>
(first, difference_type(0), difference_type(middle - first), difference_type(0), eastl::forward<value_type>(temp));
}
}
eastl::sortHeap<RandomAccessIterator>(first, middle);
}
template <typename RandomAccessIterator, typename Compare>
inline void partialSort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare compare)
{
typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type;
typedef typename eastl::iterator_traits<RandomAccessIterator>::value_type value_type;
eastl::makeHeap<RandomAccessIterator, Compare>(first, middle, compare);
for(RandomAccessIterator i = middle; i < last; ++i)
{
if(compare(*i, *first))
{
EASTL_VALIDATE_COMPARE(!compare(*first, *i)); // Validate that the compare function is sane.
value_type temp(eastl::forward<value_type>(*i));
*i = eastl::forward<value_type>(*first);
eastl::adjustHeap<RandomAccessIterator, difference_type, value_type, Compare>
(first, difference_type(0), difference_type(middle - first), difference_type(0), eastl::forward<value_type>(temp), compare);
}
}
eastl::sortHeap<RandomAccessIterator, Compare>(first, middle, compare);
}
template<typename RandomAccessIterator>
inline void nthElement(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
while((last - first) > 5)
{
const value_type midValue(eastl::median<value_type>(*first, *(first + (last - first) / 2), *(last - 1)));
const RandomAccessIterator midPos(eastl::getPartition<RandomAccessIterator, value_type>(first, last, midValue));
if(midPos <= nth)
first = midPos;
else
last = midPos;
}
eastl::insertionSort<RandomAccessIterator>(first, last);
}
template<typename RandomAccessIterator, typename Compare>
inline void nthElement(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare compare)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
while((last - first) > 5)
{
const value_type midValue(eastl::median<value_type, Compare>(*first, *(first + (last - first) / 2), *(last - 1), compare));
const RandomAccessIterator midPos(eastl::getPartition<RandomAccessIterator, value_type, Compare>(first, last, midValue, compare));
if(midPos <= nth)
first = midPos;
else
last = midPos;
}
eastl::insertionSort<RandomAccessIterator, Compare>(first, last, compare);
}
namespace Internal
{
EA_DISABLE_VC_WARNING(4702) // unreachable code
template <typename RandomAccessIterator, typename Size, typename PivotValueType>
inline void quickSort_impl_helper(RandomAccessIterator first, RandomAccessIterator last, Size kRecursionCount)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
while(((last - first) > kQuickSortLimit) && (kRecursionCount > 0))
{
const RandomAccessIterator position(eastl::getPartition<RandomAccessIterator, value_type>(first, last,
eastl::forward<PivotValueType>(eastl::median<value_type>(eastl::forward<value_type>(*first), eastl::forward<value_type>(*(first + (last - first) / 2)), eastl::forward<value_type>(*(last - 1))))));
eastl::Internal::quickSort_impl_helper<RandomAccessIterator, Size, PivotValueType>(position, last, --kRecursionCount);
last = position;
}
if(kRecursionCount == 0)
eastl::partialSort<RandomAccessIterator>(first, last, last);
}
template <typename RandomAccessIterator, typename Size, typename Compare, typename PivotValueType>
inline void quickSort_impl_helper(RandomAccessIterator first, RandomAccessIterator last, Size kRecursionCount, Compare compare)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
while(((last - first) > kQuickSortLimit) && (kRecursionCount > 0))
{
const RandomAccessIterator position(eastl::getPartition<RandomAccessIterator, value_type, Compare>(first, last,
eastl::forward<PivotValueType>(eastl::median<value_type, Compare>(eastl::forward<value_type>(*first), eastl::forward<value_type>(*(first + (last - first) / 2)), eastl::forward<value_type>(*(last - 1)), compare)), compare));
eastl::Internal::quickSort_impl_helper<RandomAccessIterator, Size, Compare, PivotValueType>(position, last, --kRecursionCount, compare);
last = position;
}
if(kRecursionCount == 0)
eastl::partialSort<RandomAccessIterator, Compare>(first, last, last, compare);
}
EA_RESTORE_VC_WARNING()
template <typename RandomAccessIterator, typename Size>
inline void quickSort_impl(RandomAccessIterator first, RandomAccessIterator last, Size kRecursionCount,
typename eastl::enable_if<eastl::is_copy_constructible<typename iterator_traits<RandomAccessIterator>::value_type>::value>::type* = 0)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;
// copy constructors require const value_type
quickSort_impl_helper<RandomAccessIterator, Size, const value_type>(first, last, kRecursionCount);
}
template <typename RandomAccessIterator, typename Size>
inline void quickSort_impl(RandomAccessIterator first, RandomAccessIterator last, Size kRecursionCount,
typename eastl::enable_if<eastl::is_move_constructible<typename iterator_traits<RandomAccessIterator>::value_type>::value
&& !eastl::is_copy_constructible<typename iterator_traits<RandomAccessIterator>::value_type>::value>::type* = 0)
{
typedef typename iterator_traits<RandomAccessIterator>::value_type value_type;