Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_sort_utils.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
94#ifndef TPL_SORT_UTILS_H
95#define TPL_SORT_UTILS_H
96
97#include <ahUtils.H>
98#include <ahFunctional.H>
99#include <ah-concepts.H>
100#include <ah-errors.H>
101#include <tpl_arrayStack.H>
102#include <tpl_array.H>
103#include <tpl_dynArray.H>
104#include <tpl_dynDlist.H>
105#include <tpl_arrayHeap.H>
106#include <htlist.H>
107#include <limits>
108#include <type_traits>
109#include <utility>
110#include <cmath>
111#include <algorithm>
112#include <ah-iterator.H>
113
114namespace Aleph {
125extern size_t Insertion_Threshold;
126
133extern size_t Quicksort_Threshold;
134
141extern const int Not_Found;
142
163template <template <typename> class Container, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
164[[nodiscard]] bool is_sorted(const Container<T> &cont, const Compare &cmp = Compare())
165{
166 if (cont.is_empty())
167 return true;
168
170 const T &first = it.get_curr();
171 const T *prev = &first;
172 it.next_ne();
173 for (; it.has_curr(); it.next_ne())
174 {
175 const T &curr = it.get_curr();
176 if (cmp(curr, *prev))
177 return false;
178 prev = &curr;
179 }
180 return true;
181}
182
205template <template <typename> class Container, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
206[[nodiscard]] std::pair<bool, size_t> search_inversion(const Container<T> &cont,
207 const Compare &cmp = Compare())
208{
209 if (cont.is_empty())
210 return std::make_pair(true, 0);
211
213 const T &first = it.get_curr();
214 const T *prev = &first;
215 size_t i = 1;
216 it.next_ne();
217 for (; it.has_curr(); it.next_ne(), ++i)
218 {
219 const T &curr = it.get_curr();
220 if (cmp(curr, *prev))
221 return std::make_pair(false, i);
222 prev = &curr;
223 }
224
225 return std::make_pair(true, i);
226}
227
247template <template <typename> class Container, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
248[[nodiscard]] bool is_inversely_sorted(const Container<T> &cont, const Compare &cmp = Compare())
249{
250 if (cont.is_empty())
251 return true;
252
254 const T &first = it.get_curr();
255 const T *prev = &first;
256 it.next_ne();
257 for (; it.has_curr(); it.next_ne())
258 {
259 const T &curr = it.get_curr();
260 if (cmp(*prev, curr))
261 return false;
262 prev = &curr;
263 }
264 return true;
265}
266
289template <template <typename> class Container, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
290[[nodiscard]] std::pair<bool, size_t> test_sorted(const Container<T> &cont,
291 const Compare &cmp = Compare())
292{
293 if (cont.is_empty())
294 return {true, 0};
295
297 const T &first = it.get_curr();
298 const T *prev = &first;
299 size_t i = 1;
300 it.next_ne();
301 for (; it.has_curr(); it.next_ne(), ++i)
302 {
303 const T &curr = it.get_curr();
304 if (cmp(curr, *prev))
305 return {false, i};
306 prev = &curr;
307 }
308 return {true, i};
309}
310
344template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
345inline void selection_sort(T *a, const size_t n, const Compare &cmp = Compare()) noexcept(
346 noexcept(static_cast<bool>(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v<T>)
347{
348 if (n < 2)
349 return;
350
351 for (size_t i = 0, min, j; i < n - 1; ++i)
352 {
353 for (min = i, j = i + 1; j < n; ++j)
354 if (cmp(a[j], a[min]))
355 min = j;
356
357 if (cmp(a[min], a[i]))
358 std::swap(a[min], a[i]);
359 }
360}
361
384template <class Link, class Compare>
385inline Link *search_extreme(const Link &list, const Compare &cmp)
386{
389 typename Link::Iterator it(const_cast<Link &>(list));
390 Link *extreme = it.get_curr();
391
392 for (it.next(); it.has_curr(); it.next_ne())
393 {
394 Link *curr = it.get_curr();
395 if (cmp(curr, extreme))
396 extreme = curr;
397 }
398
399 return extreme;
400}
401
402template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
403inline const T *search_extreme(const DynList<T> &list, const Compare &cmp = Compare())
404{
405 if (list.is_empty())
406 return nullptr;
407
409 typename DynList<T>::Const_Iterator it(list);
410 const T *extreme = &it.get_curr();
411 it.next_ne();
412 for (; it.has_curr(); it.next_ne())
413 {
414 const T &curr = it.get_curr();
415 if (cmp(curr, *extreme))
416 extreme = &curr;
417 }
418
419 return extreme;
420}
421
422template <class Compare>
423inline Dlink *search_extreme(const Dlink &list, const Compare &cmp = Compare())
424{
425 return search_extreme<Dlink, Compare>(list, cmp);
426}
427
428template <class Compare>
429inline Slinknc *search_extreme(const Slinknc &list, const Compare &cmp = Compare())
430{
431 return search_extreme<Slinknc, Compare>(list, cmp);
432}
433
443template <class Compare>
444inline void selection_sort(Dlink &list, Compare cmp)
445{
446 Dlink aux;
447 while (not list.is_empty())
448 {
449 Dlink *extreme = search_extreme<Dlink, Compare>(list, cmp);
450 extreme->del(); // remove extreme from list
451 aux.append(extreme); // insert it ordered into aux
452 }
453
454 list.swap(&aux);
455}
456
466template <typename Tlink, template <class> class Tnode, typename T, class Compare>
468{
469 Compare cmp;
470
471public:
473 Compare_Tnode(Compare cmp_fct = Compare()) noexcept(std::is_nothrow_copy_constructible_v<Compare>)
474 : cmp(cmp_fct)
475 { /* empty */
476 }
477
479 bool operator () (Tlink *l1, Tlink *l2) const
480 noexcept(noexcept(static_cast<bool>(std::declval<const Compare &>()(
481 std::declval<Tnode<T> *>()->get_data(), std::declval<Tnode<T> *>()->get_data()))))
482 {
483 auto *n1 = static_cast<Tnode<T> *>(l1);
484 auto *n2 = static_cast<Tnode<T> *>(l2);
485
486 assert(n1 == l1 and n2 == l2);
487
488 return static_cast<bool>(cmp(n1->get_data(), n2->get_data()));
489 }
490
492 bool operator () (Tlink *l, const T &x) const
493 noexcept(noexcept(static_cast<bool>(std::declval<const Compare &>()(
494 std::declval<Tnode<T> *>()->get_data(), x))))
495 {
496 auto *n = static_cast<Tnode<T> *>(l);
497
498 assert(n == l);
499
500 return static_cast<bool>(cmp(n->get_data(), x));
501 }
502};
503
507template <typename T, class Compare>
508struct Compare_Dnode : public Compare_Tnode<Dlink, Dnode, T, Compare>
509{
510 Compare_Dnode(const Compare &cmp = Compare()) noexcept(std::is_nothrow_copy_constructible_v<Compare>)
511 : Compare_Tnode<Dlink, Dnode, T, Compare>(cmp)
512 { /* empty */
513 }
514};
515
519template <typename T, class Compare>
521
529template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
530inline void selection_sort(Dnode<T> &list, Compare cmp)
531{
532 selection_sort<Compare_Dnode<T, Compare>>(list, Compare_Dnode<T, Compare>(cmp));
533}
534
556template <typename T, class Equal = Aleph::equal_to<T>>
557[[nodiscard]] inline long sequential_search(T *a, const T &x, const long l, const long r,
558 Equal eq = Equal())
559{
560 for (long i = l; i <= r; ++i)
561 if (eq(a[i], x))
562 return i;
563
564 return Not_Found;
565}
566
584template <typename T, class Equal = Aleph::equal_to<T>>
585inline long sequential_search(const DynArray<T> &a, const T &x, const long l, const long r,
586 Equal eq = Equal())
587{
588 for (long i = l; i <= r; ++i)
589 if (a.exist(i))
590 if (eq(a(i), x))
591 return i;
592
593 return Not_Found;
594}
595
608template <class Link, typename T, class Equal>
609Link *sequential_search(const Link &list, const T &x, Equal &eq)
610{
611 for (typename Link::Iterator it(const_cast<Link &>(list)); it.has_curr(); it.next_ne())
612 if (Link *curr = it.get_curr(); eq(curr, x))
613 return curr;
614
615 return nullptr;
616}
617
624template <typename T, class Equal = Aleph::equal_to<T>>
625Dlink *sequential_search(const Dlink &list, const T &x, Equal eq = Equal())
626{
629 return sequential_search<Dlink, T, Compare_Dnode<T, Equal>>(list, x, cmp);
630}
631
638template <typename T, class Equal = Aleph::equal_to<T>>
639Slinknc *sequential_search(const Slinknc &list, const T &x, Equal eq = Equal())
640{
643 return sequential_search<Slinknc, T, Compare_Snodenc<T, Equal>>(list, x, cmp);
644}
645
652template <typename T, class Equal = Aleph::equal_to<T>>
653inline Dnode<T> *sequential_search(Dnode<T> &list, const T &x, Equal &eq)
654{
657 Dlink *ret = sequential_search<Dlink, T, Compare_Dnode<T, Equal>>(list, x, cmp);
658
659 return ret == nullptr ? nullptr : static_cast<Dnode<T> *>(ret);
660}
661
663template <typename T, class Equal = Aleph::equal_to<T>>
664inline Dnode<T> *sequential_search(Dnode<T> &list, const T &x, Equal &&eq = Equal())
665{
666 return sequential_search<T, Equal>(list, x, eq);
667}
668
675template <typename T, class Equal = Aleph::equal_to<T>>
676inline const Dnode<T> *sequential_search(const Dnode<T> &list, const T &x, Equal &eq)
677{
680 const auto &base = static_cast<const Dlink &>(list);
681 const Dlink *ret = sequential_search<Dlink, T, Compare_Dnode<T, Equal>>(base, x, cmp);
682
683 return ret == nullptr ? nullptr : static_cast<const Dnode<T> *>(ret);
684}
685
687template <typename T, class Equal = Aleph::equal_to<T>>
688inline const Dnode<T> *sequential_search(const Dnode<T> &list, const T &x, Equal &&eq = Equal())
689{
690 return sequential_search<T, Equal>(list, x, eq);
691}
692
699template <typename T, class Equal = Aleph::equal_to<T>>
700inline T *sequential_search(DynDlist<T> &list, const T &x, Equal eq = Equal())
701{
702 Dnode<T> *ret = sequential_search<T, Equal>(static_cast<Dnode<T> &>(list), x, eq);
703 return ret != nullptr ? &ret->get_data() : nullptr;
704}
705
712template <typename T, class Equal = Aleph::equal_to<T>>
713inline const T *sequential_search(const DynDlist<T> &list, const T &x, Equal eq = Equal())
714{
715 const Dnode<T> *ret = sequential_search<T, Equal>(static_cast<const Dnode<T> &>(list), x, eq);
716 return ret != nullptr ? &ret->get_data() : nullptr;
717}
718
725template <typename T, class Equal = Aleph::equal_to<T>>
726inline T *sequential_search(DynList<T> &list, const T &x, Equal eq = Equal())
727{
728 for (typename DynList<T>::Iterator it(list); it.has_curr(); it.next_ne())
729 {
730 T &curr = it.get_curr_ne();
731 if (eq(curr, x))
732 return &curr;
733 }
734 return nullptr;
735}
736
743template <typename T, class Equal = Aleph::equal_to<T>>
744inline const T *sequential_search(const DynList<T> &list, const T &x, Equal eq = Equal())
745{
746 for (typename DynList<T>::Const_Iterator it(list); it.has_curr(); it.next_ne())
747 {
748 const T &curr = it.get_curr_ne();
749 if (eq(curr, x))
750 return &curr;
751 }
752 return nullptr;
753}
754
769template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
770inline long search_extreme(T *a, const long l, const long r, const Compare &cmp = Compare())
771{
772 long extreme_index = l;
773 for (long i = l + 1; i <= r; ++i)
774 if (cmp(a[i], a[extreme_index])) // is there a new minimum?
775 extreme_index = i; // yes
776
777 return extreme_index;
778}
779
784template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
785inline long search_min(T *a, const long l, const long r, const Compare &cmp = Compare())
786{
787 return search_extreme<T, Compare>(a, l, r, cmp);
788}
789
794template <typename T, StrictWeakOrder<T> Compare = Aleph::greater<T>>
795inline long search_max(T *a, const long l, const long r, const Compare &cmp = Compare())
796{
797 return search_extreme<T, Compare>(a, l, r, cmp);
798}
799
803template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
804inline Dnode<T> *search_extreme(const Dnode<T> &list, const Compare &cmp = Compare())
805{
807 Dlink *ret = search_extreme<Dlink, Compare_Dnode<T, Compare>>(
808 const_cast<Dlink &>(static_cast<const Dlink &>(list)), cmp_dnode);
809
810 return static_cast<Dnode<T> *>(ret);
811}
812
823template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
824inline T *search_extreme(DynDlist<T> &list, const Compare &cmp = Compare())
825{
826 const auto &base = static_cast<const Dnode<T> &>(list);
827 Dnode<T> *ret = search_extreme<T, Compare>(const_cast<Dnode<T> &>(base), cmp);
828
829 return ret != nullptr ? &(ret->get_data()) : nullptr;
830}
831
833template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
834inline const T *search_extreme(const DynDlist<T> &list, const Compare &cmp = Compare())
835{
836 const auto &base = static_cast<const Dnode<T> &>(list);
837 Dnode<T> *ret = search_extreme<T, Compare>(const_cast<Dnode<T> &>(base), cmp);
838
839 return ret != nullptr ? &(ret->get_data()) : nullptr;
840}
841
847template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
848inline T *search_extreme(DynList<T> &list, const Compare &cmp = Compare())
849{
850 if (list.is_empty())
851 return nullptr;
852
853 typename DynList<T>::Iterator it(list);
854 T *extreme = &it.get_curr_ne();
855 it.next_ne();
856 for (; it.has_curr(); it.next_ne())
857 {
858 T &curr = it.get_curr_ne();
859 if (cmp(curr, *extreme))
860 extreme = &curr;
861 }
862
863 return extreme;
864}
865
871template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
872inline T *search_min(DynDlist<T> &list, const Compare &cmp = Compare())
873{
874 return search_extreme<T, Compare>(list, cmp);
875}
876
878template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
879inline const T *search_min(const DynDlist<T> &list, const Compare &cmp = Compare())
880{
881 return search_extreme<T, Compare>(list, cmp);
882}
883
889template <typename T, StrictWeakOrder<T> Compare = Aleph::greater<T>>
890inline T *search_max(DynDlist<T> &list, const Compare &cmp = Compare())
891{
892 return search_extreme<T, Compare>(list, cmp);
893}
894
896template <typename T, StrictWeakOrder<T> Compare = Aleph::greater<T>>
897inline const T *search_max(const DynDlist<T> &list, const Compare &cmp = Compare())
898{
899 return search_extreme<T, Compare>(list, cmp);
900}
901
937template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
938inline void insertion_sort(T *a, const long l, const long r, const Compare &cmp = Compare()) noexcept(
939 noexcept(static_cast<bool>(cmp(std::declval<T &>(), std::declval<T &>()))) and
940 std::is_nothrow_move_constructible_v<T> and std::is_nothrow_move_assignable_v<T>)
941{
942 if (l >= r)
943 return;
944 for (long i = l + 1, j; i <= r; ++i)
945 {
946 T tmp = std::move(a[i]); // store a[i], since it will be overwritten
947 for (j = i; j > l and static_cast<bool>(cmp(tmp, a[j - 1])); --j)
948 a[j] = std::move(a[j - 1]); // shift to the right
949
950 a[j] = std::move(tmp); // insert tmp into the gap
951 }
952}
953
967template <class Compare>
968inline void insert_sorted(Dlink &list, Dlink *p, const Compare &cmp)
969{
970 // p goes after the last item that is not greater than it, so that equal
971 // items keep the order in which they came
972 Dlink *q = list.get_last();
973 while (q != &list and static_cast<bool>(cmp(p, q)))
974 q = q->get_prev();
975 q->insert(p); // after q, or first if q is the header
976}
977
978template <class Compare>
979inline void insert_sorted(HTList &list, Slinknc *p, const Compare &cmp)
980{
981 // p goes after the items that are not greater, so that equal items keep
982 // the order in which they came
983 if (list.is_empty() or static_cast<bool>(cmp(p, list.get_first()))) // p < first
984 {
985 list.insert(p);
986 return;
987 }
988
989 if (not static_cast<bool>(cmp(p, list.get_last()))) // p >= last
990 {
991 list.append(p);
992 return;
993 }
994
995 Slinknc *prev = list.get_first();
996 HTList::Iterator it(list);
997 for (it.next(); it.has_curr(); it.next_ne())
998 {
999 Slinknc *curr = it.get_curr();
1000 if (cmp(p, curr)) // p < curr
1001 {
1002 prev->insert(p);
1003 return;
1004 }
1005 prev = curr;
1006 }
1007 ah_logic_error() << "insert_sorted(): reached end of list traversal without inserting";
1008}
1009
1017template <class ListType, class Compare>
1018inline void list_insertion_sort(ListType &list, const Compare &cmp)
1019{
1020 if (list.is_empty())
1021 return;
1022
1023 ListType aux;
1024 aux.append(list.remove_first());
1025
1026 // Only the comparison can throw, before the node is linked; then the
1027 // node, the sorted ones and the rest go back to list
1028 if constexpr (noexcept(static_cast<bool>(cmp(aux.get_first(), aux.get_first()))))
1029 while (not list.is_empty())
1030 insert_sorted<Compare>(aux, list.remove_first(), cmp);
1031 else
1032 {
1033 decltype(list.remove_first()) p = nullptr;
1034 try
1035 {
1036 while (not list.is_empty())
1037 {
1038 p = list.remove_first();
1039 insert_sorted<Compare>(aux, p, cmp);
1040 }
1041 }
1042 catch (...)
1043 {
1044 aux.append(p);
1045 aux.concat_list(list);
1046 list.swap(aux);
1047 throw;
1048 }
1049 }
1050
1051 list.swap(aux);
1052}
1053
1061template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1062inline void insertion_sort(DynList<T> &l, const Compare &cmp = Compare())
1063{
1065 Cmp c(cmp);
1066 list_insertion_sort<HTList, Cmp>(l, c);
1067}
1068
1080template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1081inline DynList<T> insertion_sort(DynList<T> &&l, const Compare &cmp = Compare())
1082{
1084 Cmp c(cmp);
1085 list_insertion_sort<HTList, Cmp>(l, c);
1086 return std::move(l);
1087}
1088
1096template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1097inline void insertion_sort(Dnode<T> &list, const Compare &cmp = Compare())
1098{
1100 Cmp c(cmp);
1101 list_insertion_sort<Dlink, Cmp>(list, c);
1102}
1103
1113template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1114inline void insertion_sort(DynDlist<T> &list, const Compare &cmp = Compare())
1115{
1116 insertion_sort<T, Compare>(static_cast<Dnode<T> &>(list), cmp);
1117}
1118
1149template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1150inline void merge(T *a, const long l, const long m, const long r, Array<T> &buf,
1151 const Compare &cmp = Compare())
1152{
1153 const long s = m - l + 1; // the first partition
1154
1155 // Grow the buffer's logical size once instead of multiple push_back
1156 // calls. Array::putn() is additive (adds to the current logical size)
1157 // and only reallocates past the current capacity, so once `buf` has
1158 // grown to the largest `s` needed across the whole sort, every further
1159 // call here is O(1): just bumping the size counter back down would be
1160 // wrong (contents get fully overwritten below regardless), so the
1161 // buffer is deliberately never shrunk between merges.
1162 if (buf.size() < static_cast<size_t>(s))
1163 buf.putn(static_cast<size_t>(s) - buf.size());
1164
1165 // Move left partition [l..m] to buffer start; b reaches it without the
1166 // range checks of buf[], which could throw
1167 T *const b = &buf.base();
1168 for (long i = 0; i < s; ++i)
1169 b[i] = std::move(a[l + i]);
1170
1171 // Merge it with the right partition, which is in place: the next place
1172 // to write, k, is never past the next element of the right one, j. An
1173 // element of the right one goes first only if it is smaller.
1174 long i = 0;
1175 long j = m + 1;
1176 long k = l;
1177 if constexpr (noexcept(static_cast<bool>(cmp(a[l], a[l]))))
1178 while (i < s and j <= r)
1179 if (cmp(a[j], b[i]))
1180 a[k++] = std::move(a[j++]);
1181 else
1182 a[k++] = std::move(b[i++]);
1183 else
1184 try
1185 {
1186 while (i < s and j <= r)
1187 if (cmp(a[j], b[i]))
1188 a[k++] = std::move(a[j++]);
1189 else
1190 a[k++] = std::move(b[i++]);
1191 }
1192 catch (...)
1193 {
1194 // the s - i elements left in b fill the j - k places left in a
1195 while (i < s)
1196 a[k++] = std::move(b[i++]);
1197 throw;
1198 }
1199
1200 while (i < s) // what is left of the right partition is in place
1201 a[k++] = std::move(b[i++]);
1202}
1203
1218template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1219inline void merge(T *a, const long l, const long m, const long r, const Compare &cmp = Compare())
1220{
1221 auto buf = Array<T>::create_reserved(static_cast<size_t>(m - l + 1));
1222 merge(a, l, m, r, buf, cmp);
1223}
1224
1232template <typename T, class Compare>
1233void mergesort(T *a, const long l, const long r, Array<T> &buf, Compare cmp)
1234{
1235 if (l >= r)
1236 return;
1237
1238 const long m = l + (r - l) / 2;
1239
1240 mergesort<T, Compare>(a, l, m, buf, cmp);
1241 mergesort<T, Compare>(a, m + 1, r, buf, cmp);
1242
1243 if (not cmp(a[m + 1], a[m]))
1244 return;
1245
1246 merge<T, Compare>(a, l, m, r, buf, cmp);
1247}
1248
1283template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1284inline void mergesort(T *a, const long l, const long r, const Compare &cmp = Compare())
1285{
1286 if (l >= r)
1287 return;
1288
1289 // room for the largest first partition of a merge
1290 auto buf = Array<T>::create_reserved(static_cast<size_t>((r - l) / 2 + 1));
1291 mergesort(a, l, r, buf, cmp);
1292}
1293
1320template <typename Tlist, class Compare>
1321inline void merge_lists(Tlist &l1, Tlist &l2, Tlist &result, const Compare &cmp = Compare())
1322{
1323 assert(result.is_empty());
1324
1325 // with equal items, that of l1 goes first, so that the merge is stable
1326 while (not l1.is_empty() and not l2.is_empty())
1327 if (not static_cast<bool>(cmp(l2.get_first_ne(), l1.get_first_ne())))
1328 result.append(l1.remove_first_ne());
1329 else
1330 result.append(l2.remove_first_ne());
1331
1332 if (l1.is_empty())
1333 result.concat_list(l2);
1334 else
1335 result.concat_list(l1);
1336
1337 assert(l1.is_empty() and l2.is_empty());
1338}
1339
1349template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1350inline void merge_lists(Dnode<T> &l1, Dnode<T> &l2, Dnode<T> &result, const Compare &cmp = Compare())
1351{
1352 merge_lists<Dnode<T>, Compare_Dnode<T, Compare>>(l1, l2, result, cmp);
1353}
1354
1387template <typename Tlist, class Compare>
1388inline void mergesort(Tlist &list, const Compare &cmp = Compare())
1389{
1390 if (list.is_unitarian_or_empty())
1391 return;
1392
1393 Tlist l, r;
1394 list.split_list_ne(l, r); // split into two lists
1395
1396 // Only the comparison can throw; then what is not merged yet goes back
1397 // to list. A comparison that does not throw needs no handler, which
1398 // would change the code of the sort.
1399 if constexpr (noexcept(static_cast<bool>(cmp(l.get_first_ne(), r.get_first_ne()))))
1400 {
1401 mergesort<Tlist, Compare>(l, cmp);
1402 mergesort<Tlist, Compare>(r, cmp);
1403
1404 merge_lists<Tlist, Compare>(l, r, list, cmp); // merge them
1405 }
1406 else
1407 try
1408 {
1409 mergesort<Tlist, Compare>(l, cmp);
1410 mergesort<Tlist, Compare>(r, cmp);
1411
1412 merge_lists<Tlist, Compare>(l, r, list, cmp); // merge them
1413 }
1414 catch (...)
1415 {
1416 list.concat_list(l);
1417 list.concat_list(r);
1418 throw;
1419 }
1420}
1421
1422// Sorts the n nodes of list by mergesort down to lists of at most lsz
1423// nodes, which are sorted by insertion. The nodes are linked again, so that
1424// nothing is allocated. Only the comparison can throw; then list keeps all
1425// its nodes, in an unspecified order.
1426template <class Tlist, class Tlink, class Compare>
1427inline void __link_mergeinsertsort(Tlist &list, const size_t n, const Compare &cmp, const size_t lsz)
1428{
1429 if (n <= 1)
1430 return;
1431
1432 if (n <= lsz)
1433 {
1434 list_insertion_sort<Tlink, Compare>(list, cmp);
1435 return;
1436 }
1437
1438 Tlist l, r;
1439 list.split_list_ne(l, r); // l takes the first n - n / 2 nodes
1440 const size_t nl = n - n / 2;
1441
1442 if constexpr (noexcept(static_cast<bool>(cmp(l.get_first_ne(), r.get_first_ne()))))
1443 {
1444 __link_mergeinsertsort<Tlist, Tlink, Compare>(l, nl, cmp, lsz);
1445 __link_mergeinsertsort<Tlist, Tlink, Compare>(r, n - nl, cmp, lsz);
1446 merge_lists<Tlist, Compare>(l, r, list, cmp);
1447 }
1448 else
1449 try
1450 {
1451 __link_mergeinsertsort<Tlist, Tlink, Compare>(l, nl, cmp, lsz);
1452 __link_mergeinsertsort<Tlist, Tlink, Compare>(r, n - nl, cmp, lsz);
1453 merge_lists<Tlist, Compare>(l, r, list, cmp);
1454 }
1455 catch (...)
1456 {
1457 list.concat_list(l);
1458 list.concat_list(r);
1459 throw;
1460 }
1461}
1462
1481template <template <typename> class Tlist, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1482inline void mergeinsertsort(Tlist<T> &list, const Compare &cmp = Compare(),
1483 const size_t lsz = Aleph::Insertion_Threshold)
1484{
1485 if (list.is_unitarian_or_empty())
1486 return;
1487
1488 if constexpr (std::is_same_v<Tlist<T>, DynList<T>>)
1489 {
1491 __link_mergeinsertsort<HTList, HTList, Cmp>(list, list.size(), Cmp(cmp), lsz);
1492 }
1493 else if constexpr (std::is_same_v<Tlist<T>, DynDlist<T>>)
1494 {
1496 __link_mergeinsertsort<Dnode<T>, Dlink, Cmp>(list, list.size(), Cmp(cmp), lsz);
1497 }
1498 else
1499 {
1500 if (list.size() <= lsz)
1501 {
1502 insertion_sort<T, Compare>(list, cmp);
1503 return;
1504 }
1505
1506 Tlist<T> l, r;
1507 list.split_list(l, r); // split into two lists
1508
1509 try
1510 {
1511 mergeinsertsort<Tlist, T, Compare>(l, cmp, lsz);
1512 mergeinsertsort<Tlist, T, Compare>(r, cmp, lsz);
1513
1514 merge_lists<Tlist<T>, Compare>(l, r, list, cmp); // merge them
1515 }
1516 catch (...)
1517 {
1518 list.concat_list(l);
1519 list.concat_list(r);
1520 throw;
1521 }
1522 }
1523}
1524
1533template <template <typename> class Tlist, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1534inline void mergesort(Tlist<T> &list, const Compare &cmp = Compare())
1535{
1536 if constexpr (std::is_same_v<Tlist<T>, DynList<T>> or std::is_same_v<Tlist<T>, DynDlist<T>>)
1537 mergesort<T, Compare>(list, cmp); // they link their nodes again
1538 else
1539 mergesort<Tlist<T>, Compare>(list, cmp);
1540}
1541
1549template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1550inline void mergesort(Dnode<T> &list, const Compare &cmp = Compare())
1551{
1552 mergesort<Dnode<T>, Compare_Dnode<T, Compare>>(list, cmp);
1553}
1554
1562template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1563inline void mergesort(DynDlist<T> &list, const Compare &cmp = Compare())
1564{
1565 mergesort<Dnode<T>, Compare_Dnode<T, Compare>>(list, cmp);
1566}
1567
1580template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1581inline void mergesort(DynList<T> &list, const Compare &cmp = Compare())
1582{
1583 // the nodes are linked again, so that nothing is allocated; the
1584 // comparison is not copied
1586 mergesort<HTList, Cmp>(list, Cmp(cmp));
1587}
1588
1599template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1600inline DynList<T> mergesort(DynList<T> &&list, const Compare &cmp = Compare())
1601{
1602 mergesort<T, Compare>(list, cmp);
1603 return std::move(list);
1604}
1605
1613template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1614inline long select_pivot(T *a, long l, long r, const Compare &cmp = Compare()) noexcept(
1615 noexcept(static_cast<bool>(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v<T>);
1616
1634template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1635inline long partition(T *a, const long l, const long r, const Compare &cmp = Compare()) noexcept(
1636 noexcept(static_cast<bool>(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v<T>)
1637{
1638 if (l >= r)
1639 return l;
1640
1641 const long p = select_pivot<T, Compare>(a, l, r, cmp);
1643 std::swap(a[p], a[r]);
1644
1645 // Note: pivot stays at a[r] throughout the loop - no copy needed
1646 // This saves a potentially expensive copy for large T types
1647 long i = l - 1; // index first element to the left > pivot
1648 long j = r; // index first element to the right < pivot
1649 while (true)
1650 {
1651 // advance while a[i] < pivot (pivot is at a[r])
1652 while (cmp(a[++i], a[r]))
1653 ;
1654
1655 while (cmp(a[r], a[--j])) // advance while pivot < a[j]
1656 if (j == l) // Has the left edge been reached?
1657 break; // yes ==> the iteration must be finished
1658
1659 if (i >= j)
1660 break;
1661
1663 std::swap(a[i], a[j]); // Eliminate inversion
1664 }
1665
1667 std::swap(a[i], a[r]); // Place pivot in its final position
1668
1669 return i;
1670}
1671
1690template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1691inline void quicksort_rec(T *a, const long l, const long r, const Compare &cmp = Compare())
1692{
1693 if (l >= r)
1694 return;
1695
1696 const long pivot = partition<T, Compare>(a, l, r, cmp);
1697
1698 quicksort_rec<T, Compare>(a, l, pivot - 1, cmp);
1699 quicksort_rec<T, Compare>(a, pivot + 1, r, cmp);
1700}
1701
1715template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1716inline void quicksort_no_tail(T *a, long l, long r, const Compare &cmp = Compare())
1717{
1718 while (l < r)
1719 {
1720 const long pivot = partition<T, Compare>(a, l, r, cmp);
1721 const long left_size = pivot - l;
1722 const long right_size = r - pivot;
1723
1724 // Recurse on the smaller partition to ensure O(log n) stack depth.
1725 if (left_size < right_size)
1726 {
1727 quicksort_no_tail<T, Compare>(a, l, pivot - 1, cmp);
1728 l = pivot + 1; // tail recurse on the right by looping
1729 }
1730 else
1731 {
1732 quicksort_no_tail<T, Compare>(a, pivot + 1, r, cmp);
1733 r = pivot - 1; // tail recurse on the left by looping
1734 }
1735 }
1736}
1737
1754template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1755inline void quicksort_rec_min(T *a, const long l, const long r, const Compare &cmp = Compare())
1756{
1757 if (r <= l)
1758 return;
1759
1760 if (const long pivot = partition<T, Compare>(a, l, r, cmp); pivot - l < r - pivot)
1761 // which partition is smaller?
1762 { // left partition is smaller
1763 quicksort_rec_min<T, Compare>(a, l, pivot - 1, cmp);
1764 quicksort_rec_min<T, Compare>(a, pivot + 1, r, cmp);
1765 }
1766 else
1767 { // right partition is smaller
1768 quicksort_rec_min<T, Compare>(a, pivot + 1, r, cmp);
1769 quicksort_rec_min<T, Compare>(a, l, pivot - 1, cmp);
1770 }
1771}
1772
1773template <typename T, StrictWeakOrder<T> Compare>
1774inline long select_pivot(T *a, const long l, const long r, const Compare &cmp) noexcept(
1775 noexcept(static_cast<bool>(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v<T>)
1776{
1777 const long m = l + (r - l) / 2;
1778
1781 if (cmp(a[r], a[l]))
1782 std::swap(a[l], a[r]);
1784 if (cmp(a[m], a[l]))
1785 std::swap(a[m], a[l]);
1787 if (cmp(a[r], a[m]))
1788 std::swap(a[r], a[m]);
1789
1790 return m;
1791}
1792
1794inline size_t introsort_depth_limit(size_t n) noexcept;
1795
1833template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
1834inline void quicksort(T *a, const long l, const long r, const Compare &cmp = Compare())
1835{
1836 if (r - l < Quicksort_Threshold)
1837 {
1838 insertion_sort(a, l, r, cmp);
1839 return;
1840 }
1841
1842 const auto n = static_cast<size_t>(r - l + 1);
1843
1844 typedef std::pair<long, long> Partition;
1847 stack.push(Partition(l, r));
1848
1849 while (stack.size() > 0)
1850 {
1851 auto [fst, snd] = stack.pop();
1852 const long diff = snd - fst;
1853
1854 if (diff <= 0)
1855 continue;
1856
1858 {
1859 insertion_sort(a, fst, snd, cmp);
1860 continue;
1861 }
1862
1863 if (const long pivot = partition<T, Compare>(a, fst, snd, cmp); pivot - fst < snd - pivot)
1864 // which one is smaller?
1865 { // the left partition is smaller
1866 stack.push(Partition(pivot + 1, snd));
1867 stack.push(Partition(fst, pivot - 1));
1868 }
1869 else
1870 { // the right partition is smaller
1871 stack.push(Partition(fst, pivot - 1));
1872 stack.push(Partition(pivot + 1, snd));
1873 }
1874 }
1875}
1876
1885inline size_t introsort_depth_limit(size_t n) noexcept
1886{
1887 size_t depth = 0;
1888 while (n > 1)
1889 {
1890 n >>= 1;
1891 ++depth;
1892 }
1893 return depth * 2;
1894}
1895
1901template <typename T, class Compare>
1902void introsort_loop(T *a, long l, long r, size_t depth_limit, const Compare &cmp)
1903{
1904 while (r - l >= static_cast<long>(Quicksort_Threshold))
1905 {
1906 if (depth_limit == 0) [[unlikely]]
1907 {
1908 // Depth limit reached: switch to heapsort for guaranteed O(n log n)
1909 faster_heapsort(a + l, static_cast<size_t>(r - l + 1), cmp);
1910 return;
1911 }
1912
1913 --depth_limit;
1914
1915 // Median-of-three pivot selection
1916 // Recurse on smaller partition, iterate on larger (tail call elimination)
1917 if (const long pivot = partition<T, Compare>(a, l, r, cmp); pivot - l < r - pivot)
1918 {
1919 introsort_loop<T, Compare>(a, l, pivot - 1, depth_limit, cmp);
1920 l = pivot + 1;
1921 }
1922 else
1923 {
1924 introsort_loop<T, Compare>(a, pivot + 1, r, depth_limit, cmp);
1925 r = pivot - 1;
1926 }
1927 }
1928}
1929
1938namespace pdq_detail {
1940inline constexpr long Insertion_Threshold = 24;
1941
1943inline constexpr long Ninther_Threshold = 128;
1944
1948inline constexpr long Partial_Insertion_Limit = 8;
1949
1951inline constexpr long Block_Size = 64;
1952
1957inline constexpr long Few_Swaps_Ratio = 16;
1958
1963template <typename T>
1964using Pivot_Ref = std::conditional_t<std::is_trivially_copyable_v<T>, const T, const T &>;
1965
1969template <typename T>
1976
1978template <typename T, class Compare>
1979inline void sort2(T *a, T *b, const Compare &cmp)
1980{
1981 if (cmp(*b, *a))
1982 std::iter_swap(a, b);
1983}
1984
1986template <typename T, class Compare>
1987inline void sort3(T *a, T *b, T *c, const Compare &cmp)
1988{
1989 pdq_detail::sort2(a, b, cmp);
1990 pdq_detail::sort2(b, c, cmp);
1991 pdq_detail::sort2(a, b, cmp);
1992}
1993
2002template <bool Guarded, typename T, class Compare>
2003inline T *insert_back(T *begin, T *cur, const Compare &cmp)
2004{
2005 T item = std::move(*cur);
2006 T *hole = cur;
2007 try
2008 {
2009 do
2010 {
2011 *hole = std::move(*(hole - 1));
2012 --hole;
2013 }
2014 while ((not Guarded or hole != begin) and cmp(item, *(hole - 1)));
2015 }
2016 catch (...)
2017 {
2018 *hole = std::move(item);
2019 throw;
2020 }
2021 *hole = std::move(item);
2022 return hole;
2023}
2024
2030template <bool Guarded, typename T, class Compare>
2031void insertion_sort_range(T *begin, T *end, const Compare &cmp)
2032{
2033 if (begin == end)
2034 return;
2035 for (T *cur = begin + 1; cur != end; ++cur)
2036 if (cmp(*cur, *(cur - 1)))
2037 pdq_detail::insert_back<Guarded>(begin, cur, cmp);
2038}
2039
2046template <typename T, class Compare>
2047bool partial_insertion_sort_range(T *begin, T *end, const Compare &cmp)
2048{
2049 if (begin == end)
2050 return true;
2051 long moves = 0;
2052 for (T *cur = begin + 1; cur != end; ++cur)
2053 {
2054 if (cmp(*cur, *(cur - 1)))
2055 moves += cur - pdq_detail::insert_back<true>(begin, cur, cmp);
2056 if (moves > Partial_Insertion_Limit)
2057 return false;
2058 }
2059 return true;
2060}
2061
2068template <typename T>
2069void swap_offsets(T *first, T *last, const unsigned char *offsets_l,
2070 const unsigned char *offsets_r, const long num, const bool use_swaps)
2071{
2072 if (use_swaps)
2073 {
2074 for (long i = 0; i < num; ++i)
2075 std::iter_swap(first + offsets_l[i], last - offsets_r[i]);
2076 return;
2077 }
2078 if (num == 0)
2079 return;
2080 T *l = first + offsets_l[0];
2081 T *r = last - offsets_r[0];
2082 T tmp = std::move(*l);
2083 *l = std::move(*r);
2084 for (long i = 1; i < num; ++i)
2085 {
2086 l = first + offsets_l[i];
2087 *r = std::move(*l);
2088 r = last - offsets_r[i];
2089 *l = std::move(*r);
2090 }
2091 *r = std::move(tmp);
2092}
2093
2104template <typename T, class Compare>
2105Partitioned<T> partition_by_blocks(T *begin, T *end, const Compare &cmp)
2106{
2107 Pivot_Ref<T> pivot = *begin;
2108 T *first = begin;
2109 T *last = end;
2110 while (cmp(*++first, pivot))
2111 ;
2112 // With no item before first that is less than the pivot, only the bound
2113 // stops the scan from the right
2114 if (first - 1 == begin)
2115 while (first < last and not cmp(*--last, pivot))
2116 ;
2117 else
2118 while (not cmp(*--last, pivot))
2119 ;
2120
2121 const bool already_partitioned = first >= last;
2122 long swapped = 0;
2123 if (not already_partitioned)
2124 {
2125 std::iter_swap(first, last);
2126 ++first;
2127 swapped = 1;
2128
2129 // The offsets of the items on the wrong side: those of the left block
2130 // from base_l, and those of the right one, from 1, back from base_r
2131 alignas(64) unsigned char offsets_l[Block_Size];
2132 alignas(64) unsigned char offsets_r[Block_Size];
2133 T *base_l = first;
2134 T *base_r = last;
2135 long num_l = 0, num_r = 0, start_l = 0, start_r = 0;
2136 while (first < last)
2137 {
2138 // An empty block takes up to Block_Size of the items not compared
2139 // yet; when both are empty, they share them
2140 const long unknown = last - first;
2141 const long left = num_l == 0 ? (num_r == 0 ? unknown / 2 : unknown) : 0;
2142 const long right = num_r == 0 ? unknown - left : 0;
2143 for (long i = 0, n = std::min(left, Block_Size); i < n; ++i)
2144 {
2145 offsets_l[num_l] = static_cast<unsigned char>(i);
2146 num_l += static_cast<long>(not cmp(*first++, pivot));
2147 }
2148 for (long i = 1, n = std::min(right, Block_Size); i <= n; ++i)
2149 {
2150 offsets_r[num_r] = static_cast<unsigned char>(i);
2151 num_r += static_cast<long>(cmp(*--last, pivot));
2152 }
2153
2154 const long num = std::min(num_l, num_r);
2155 pdq_detail::swap_offsets(base_l, base_r, offsets_l + start_l, offsets_r + start_r,
2156 num, num_l == num_r);
2157 swapped += num;
2158 num_l -= num;
2159 num_r -= num;
2160 start_l += num;
2161 start_r += num;
2162 if (num_l == 0)
2163 {
2164 start_l = 0;
2165 base_l = first;
2166 }
2167 if (num_r == 0)
2168 {
2169 start_r = 0;
2170 base_r = last;
2171 }
2172 }
2173
2174 // Every item is compared: the wrong ones of the block that is left go
2175 // across the boundary, the farthest first
2176 swapped += num_l + num_r;
2177 if (num_l > 0)
2178 {
2179 while (num_l-- > 0)
2180 std::iter_swap(base_l + offsets_l[start_l + num_l], --last);
2181 first = last;
2182 }
2183 if (num_r > 0)
2184 while (num_r-- > 0)
2185 std::iter_swap(base_r - offsets_r[start_r + num_r], first++);
2186 }
2187
2188 T *const pivot_pos = first - 1;
2189 std::iter_swap(begin, pivot_pos);
2190 return {pivot_pos, already_partitioned, swapped};
2191}
2192
2199template <typename T, class Compare>
2200Partitioned<T> partition_by_branches(T *begin, T *end, const Compare &cmp)
2201{
2202 Pivot_Ref<T> pivot = *begin;
2203 T *first = begin;
2204 T *last = end;
2205 while (cmp(*++first, pivot))
2206 ;
2207 if (first - 1 == begin)
2208 while (first < last and not cmp(*--last, pivot))
2209 ;
2210 else
2211 while (not cmp(*--last, pivot))
2212 ;
2213
2214 const bool already_partitioned = first >= last;
2215 long swapped = 0;
2216 while (first < last)
2217 {
2218 std::iter_swap(first, last);
2219 ++swapped;
2220 while (cmp(*++first, pivot))
2221 ;
2222 while (not cmp(*--last, pivot))
2223 ;
2224 }
2225
2226 T *const pivot_pos = first - 1;
2227 std::iter_swap(begin, pivot_pos);
2228 return {pivot_pos, already_partitioned, swapped};
2229}
2230
2238template <typename T, class Compare>
2239T *partition_left(T *begin, T *end, const Compare &cmp)
2240{
2241 Pivot_Ref<T> pivot = *begin;
2242 T *first = begin;
2243 T *last = end;
2244 while (cmp(pivot, *--last))
2245 ;
2246 if (last + 1 == end)
2247 while (first < last and not cmp(pivot, *++first))
2248 ;
2249 else
2250 while (not cmp(pivot, *++first))
2251 ;
2252 while (first < last)
2253 {
2254 std::iter_swap(first, last);
2255 while (cmp(pivot, *--last))
2256 ;
2257 while (not cmp(pivot, *++first))
2258 ;
2259 }
2260 std::iter_swap(begin, last);
2261 return last;
2262}
2263
2279template <typename T, class Compare>
2280void sort_loop(T *begin, T *end, const Compare &cmp, int bad_allowed, bool leftmost,
2281 bool by_blocks)
2282{
2283 while (true)
2284 {
2285 const long size = end - begin;
2287 {
2288 if (leftmost)
2289 pdq_detail::insertion_sort_range<true>(begin, end, cmp);
2290 else
2291 pdq_detail::insertion_sort_range<false>(begin, end, cmp);
2292 return;
2293 }
2294
2295 // The pivot goes to begin: the median of three items, or of nine
2296 if (const long s2 = size / 2; size > Ninther_Threshold)
2297 {
2298 pdq_detail::sort3(begin, begin + s2, end - 1, cmp);
2299 pdq_detail::sort3(begin + 1, begin + (s2 - 1), end - 2, cmp);
2300 pdq_detail::sort3(begin + 2, begin + (s2 + 1), end - 3, cmp);
2301 pdq_detail::sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), cmp);
2302 std::iter_swap(begin, begin + s2);
2303 }
2304 else
2305 pdq_detail::sort3(begin + s2, begin, end - 1, cmp);
2306
2307 // A pivot equal to the item before the range: the items equal to it
2308 // go to their places in one pass
2309 if (not leftmost and not cmp(*(begin - 1), *begin))
2310 {
2311 begin = pdq_detail::partition_left(begin, end, cmp) + 1;
2312 continue;
2313 }
2314
2315 const auto [pivot_pos, already_partitioned, swapped] =
2316 by_blocks ? pdq_detail::partition_by_blocks(begin, end, cmp)
2318 by_blocks = swapped * Few_Swaps_Ratio > size;
2319 const long l_size = pivot_pos - begin;
2320 const long r_size = end - (pivot_pos + 1);
2321 if (l_size < size / 8 or r_size < size / 8)
2322 {
2323 // A highly unbalanced partition: after too many of them, heapsort
2324 // bounds the cost by O(n log n); before, some swaps break the
2325 // pattern of the input
2326 if (--bad_allowed == 0)
2327 {
2328 faster_heapsort(begin, static_cast<size_t>(size), cmp);
2329 return;
2330 }
2331 if (l_size >= Insertion_Threshold)
2332 {
2333 std::iter_swap(begin, begin + l_size / 4);
2334 std::iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
2335 if (l_size > Ninther_Threshold)
2336 {
2337 std::iter_swap(begin + 1, begin + (l_size / 4 + 1));
2338 std::iter_swap(begin + 2, begin + (l_size / 4 + 2));
2339 std::iter_swap(pivot_pos - 2, pivot_pos - (l_size / 4 + 1));
2340 std::iter_swap(pivot_pos - 3, pivot_pos - (l_size / 4 + 2));
2341 }
2342 }
2343 if (r_size >= Insertion_Threshold)
2344 {
2345 std::iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
2346 std::iter_swap(end - 1, end - r_size / 4);
2347 if (r_size > Ninther_Threshold)
2348 {
2349 std::iter_swap(pivot_pos + 2, pivot_pos + (2 + r_size / 4));
2350 std::iter_swap(pivot_pos + 3, pivot_pos + (3 + r_size / 4));
2351 std::iter_swap(end - 2, end - (1 + r_size / 4));
2352 std::iter_swap(end - 3, end - (2 + r_size / 4));
2353 }
2354 }
2355 }
2356 else if (already_partitioned
2359 return; // the range was in order, or nearly
2360
2361 // The left side by recursion, and the right one by iteration
2362 pdq_detail::sort_loop(begin, pivot_pos, cmp, bad_allowed, leftmost, by_blocks);
2363 begin = pivot_pos + 1;
2364 leftmost = false;
2365 }
2366}
2367} // namespace pdq_detail
2368
2426template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2427inline void introsort(T *a, const long l, const long r, const Compare &cmp = Compare())
2428{
2429 if (r <= l)
2430 return;
2431 int log2_n = 0;
2432 for (auto n = static_cast<size_t>(r - l + 1); n > 1; n >>= 1)
2433 ++log2_n;
2434 pdq_detail::sort_loop(a + l, a + r + 1, cmp, log2_n, true, true);
2435}
2436
2448template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2449inline void introsort(T *a, const size_t n, const Compare &cmp = Compare())
2450{
2451 if (n <= 1)
2452 return;
2453 introsort(a, 0L, static_cast<long>(n - 1), cmp);
2454}
2455
2483template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2484inline void introsort(T *begin, T *end, const Compare &cmp = Compare())
2485{
2486 if (begin >= end)
2487 return;
2488 const auto n = static_cast<size_t>(end - begin);
2489 introsort(begin, n, cmp);
2490}
2491
2499template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2500inline void introsort(Array<T> &arr, const Compare &cmp = Compare())
2501{
2502 const size_t n = arr.size();
2503 if (n <= 1)
2504 return;
2505 // Array uses contiguous memory via MemArray, so we can use pointer arithmetic
2506 introsort(&arr(0), n, cmp);
2507}
2508
2522template <class Compare>
2523void quicksort(Dlink &list, const Compare &cmp = Compare())
2524{
2525 if (list.is_unitarian_or_empty())
2526 return;
2527
2528 Dlink *pivot = list.remove_next();
2529 Dlink smaller, bigger; // lists of smaller and larger than pivot
2530
2531 while (not list.is_empty())
2532 if (Dlink *p = list.remove_next(); cmp(p, pivot))
2533 smaller.append(p);
2534 else
2535 bigger.append(p);
2536
2537 quicksort<Compare>(bigger, cmp);
2538 quicksort<Compare>(smaller, cmp);
2539
2540 list.concat_list(&smaller); // restore sorted lists into list
2541 list.append(pivot);
2542 list.concat_list(&bigger);
2543}
2544
2566template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2567void quicksort(Dnode<T> &list, const Compare &cmp = Compare())
2568{
2569 quicksort<Compare_Dnode<T, Compare>>(list, cmp);
2570}
2571
2576template <typename T, class Compare>
2577void quicksort(HTList &list, const Compare &cmp = Compare())
2578{
2579 if (list.is_unitarian_or_empty())
2580 return;
2581
2582 auto *pivot = static_cast<Snodenc<T> *>(list.remove_first_ne());
2583 HTList smaller, bigger; // lists of smaller and larger than pivot
2584
2585 while (not list.is_empty())
2586 if (auto *p = static_cast<Snodenc<T> *>(list.remove_first_ne());
2587 cmp(p->get_data(), pivot->get_data()))
2588 smaller.append(p);
2589 else
2590 bigger.append(p);
2591
2592 quicksort<T, Compare>(bigger, cmp);
2593 quicksort<T, Compare>(smaller, cmp);
2594
2595 list.concat_list(smaller); // restore sorted lists into list
2596 list.append(pivot);
2597 list.concat_list(bigger);
2598}
2599
2604template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2605void quicksort(DynList<T> &list, const Compare &cmp = Compare())
2606{
2607 quicksort<T, Compare>(static_cast<HTList &>(list), cmp);
2608}
2609
2648template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2649inline void quicksort_insertion(T *a, const long l, const long r, const Compare &cmp = Compare())
2650{
2651 if (r <= l)
2652 return;
2653
2654 const long pivot = partition<T, Compare>(a, l, r, cmp);
2655
2656 const long l_size = pivot - l; // left partition size
2657 const long r_size = r - pivot; // right partition size
2658 bool left_done = false; // true if left partition is sorted
2659 bool right_done = false; // true if der partition is sorted
2660
2661 if (l_size <= Aleph::Insertion_Threshold)
2662 { // sort left partition by insertion
2663 insertion_sort<T, Compare>(a, l, pivot - 1, cmp);
2664 left_done = true;
2665 }
2666
2667 if (r_size <= Aleph::Insertion_Threshold)
2668 { // sort der partition by insertion
2669 insertion_sort<T, Compare>(a, pivot + 1, r, cmp);
2670 right_done = true;
2671 }
2672
2673 if (left_done and right_done)
2674 return; // both partitions sorted by insertion
2675
2676 if (left_done) // left partition sorted by insertion?
2677 { // Yeah; It only remains to recursively sort the right partition
2678 quicksort_insertion<T, Compare>(a, pivot + 1, r, cmp);
2679 return;
2680 }
2681
2682 if (right_done) // der partition sorted by insertion?
2683 { // Yeah; It only remains to recursively sort the left partition
2684 quicksort_insertion<T, Compare>(a, l, pivot - 1, cmp);
2685 return;
2686 }
2687
2688 // here, both partitions were not insertion sorted
2689 if (l_size < r_size) // sort smallest partition first
2690 { // smaller left partition
2691 quicksort_insertion<T, Compare>(a, l, pivot - 1, cmp);
2692 quicksort_insertion<T, Compare>(a, pivot + 1, r, cmp);
2693 }
2694 else
2695 { // smaller right partition
2696 quicksort_insertion<T, Compare>(a, pivot + 1, r, cmp);
2697 quicksort_insertion<T, Compare>(a, l, pivot - 1, cmp);
2698 }
2699}
2700
2734template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2735inline long random_search(T *a, const T &x, const long l, const long r,
2736 const Compare &cmp = Compare())
2737{
2738 if (l > r)
2739 return Not_Found;
2740
2741 const long pivot = partition<T, Compare>(a, l, r, cmp);
2742
2743 if (cmp(x, a[pivot]))
2744 return random_search<T, Compare>(a, x, l, pivot - 1, cmp);
2745 if (cmp(a[pivot], x))
2746 return random_search<T, Compare>(a, x, pivot + 1, r, cmp);
2747
2748 return pivot; // element found at index x
2749}
2750
2759template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2760inline long random_search(DynArray<T> &a, const T &x, const long l, const long r,
2761 const Compare &cmp = Compare())
2762{
2763 if (l > r)
2764 return Not_Found;
2765
2766 const long pivot = partition(a, l, r, cmp);
2767
2768 if (cmp(x, a(pivot)))
2769 return random_search<T, Compare>(a, x, l, pivot - 1, cmp);
2770 if (cmp(a(pivot), x))
2771 return random_search<T, Compare>(a, x, pivot + 1, r, cmp);
2772
2773 return pivot; // element found at index x
2774}
2775
2802template <typename T, class Compare>
2803inline Dnode<T> *dlink_random_search(Dlink &list, const T &x, const Compare &cmp = Compare())
2804{
2805 if (list.is_empty())
2806 return nullptr;
2807
2810 Dnode<T> item(x);
2811 Dnode<T> *item_ptr = &item; // pointer to the cell containing x
2812
2813 Dlink smaller; // list of those smaller than pivot
2814 Dlink bigger; // list of those greater than pivot
2815
2816 auto *pivot = static_cast<Dnode<T> *>(list.remove_next());
2817
2818 while (not list.is_empty())
2819 if (Dlink *p = list.remove_next(); cmp(p, pivot))
2820 smaller.append(p);
2821 else
2822 bigger.append(p);
2823
2824 Dnode<T> *ret_val = nullptr;
2825 if (cmp(item_ptr, pivot))
2826 ret_val = dlink_random_search<T, Compare>(smaller, x, cmp);
2827 else if (cmp(pivot, item_ptr))
2828 ret_val = dlink_random_search<T, Compare>(bigger, x, cmp);
2829 else
2830 ret_val = pivot;
2831
2832 assert(list.is_empty());
2833
2834 list.swap(&smaller);
2835 list.append(pivot);
2836 list.concat_list(&bigger);
2837
2838 return ret_val;
2839}
2840
2870template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2871Dnode<T> *random_search(Dlink &list, const T &x, const Compare &cmp = Compare())
2872{
2873 return dlink_random_search<T, Compare_Dnode<T, Compare>>(list, x, cmp);
2874}
2875
2905template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
2906inline T *random_search(DynDlist<T> &list, const T &x, const Compare &cmp = Compare())
2907{
2908 Dnode<T> *p = dlink_random_search<T, Compare_Dnode<T, Compare>>(list, x, cmp);
2909
2910 return p == nullptr ? nullptr : &(p->get_data());
2911}
2912
2913template <typename T, class Compare>
2914static inline std::pair<long, long> partition_three_way(T *a, long l, long r, const Compare &cmp)
2915{
2916 const long pivot_idx = select_pivot<T, Compare>(a, l, r, cmp);
2918 std::swap(a[pivot_idx], a[r]);
2919
2920 long lt = l;
2921 long gt = r - 1;
2922 long current = l;
2923
2924 while (current <= gt)
2925 if (cmp(a[current], a[r]))
2926 {
2927 std::swap(a[lt], a[current]);
2928 lt++;
2929 current++;
2930 }
2931 else if (cmp(a[r], a[current]))
2932 {
2933 std::swap(a[current], a[gt]);
2934 gt--;
2935 }
2936 else
2937 current++;
2938
2940 std::swap(a[current], a[r]);
2941 return {lt, current};
2942}
2943
2944template <class Container, typename T, class Compare>
2945static inline std::pair<long, long> partition_three_way_op(Container &a, long l, long r,
2946 const Compare &cmp)
2947{
2948 const long pivot_idx = select_pivot_op<T, Compare>(a, l, r, cmp);
2950 std::swap(a(pivot_idx), a(r));
2951
2952 long lt = l;
2953 long gt = r - 1;
2954 long current = l;
2955
2956 while (current <= gt)
2957 if (cmp(a(current), a(r)))
2958 {
2959 std::swap(a(lt), a(current));
2960 lt++;
2961 current++;
2962 }
2963 else if (cmp(a(r), a(current)))
2964 {
2965 std::swap(a(current), a(gt));
2966 gt--;
2967 }
2968 else
2969 current++;
2970
2972 std::swap(a(current), a(r));
2973 return {lt, current};
2974}
2975
2976template <typename T, class Compare>
2977static inline const T &__random_select(T *a, const long i, long l, long r, const Compare &cmp)
2978{
2979 while (l < r)
2980 {
2981 if (r - l < 10)
2982 {
2983 insertion_sort<T, Compare>(a, l, r, cmp);
2984 return a[i];
2985 }
2986
2987 const auto [lt, current] = partition_three_way<T, Compare>(a, l, r, cmp);
2988
2989 if (i >= lt and i <= current)
2990 return a[i];
2991
2992 if (i < lt)
2993 r = lt - 1;
2994 else
2995 l = current + 1;
2996 }
2997
2998 return a[l];
2999}
3000
3009template <typename T, class Compare, typename Container>
3010inline long select_pivot_op_impl(const Container &a, const long l, const long r, const Compare &cmp)
3011{
3012 assert(l <= r);
3013
3014 if (r - l <= 5)
3015 return r;
3016
3017 const long m = l + (r - l) / 2; // central element
3018
3019 // Access array entries only once
3020 const T &la = a(l);
3021 const T &ra = a(r);
3022 const T &ma = a(m);
3023
3024 const T *med_ptr = Aleph::median<T, Compare>(la, ma, ra, cmp);
3025
3026 if (med_ptr == &la)
3027 return l;
3028
3029 if (med_ptr == &ma)
3030 return m;
3031
3032 assert(med_ptr == &ra);
3033
3034 return r;
3035}
3036
3042template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3043inline long select_pivot_op(const DynArray<T> &a, const long l, const long r,
3044 const Compare &cmp = Compare())
3045{
3046 return select_pivot_op_impl<T, Compare>(a, l, r, cmp);
3047}
3048
3054template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3055inline long select_pivot_op(const Array<T> &a, const long l, const long r,
3056 const Compare &cmp = Compare())
3057{
3058 return select_pivot_op_impl<T, Compare>(a, l, r, cmp);
3059}
3060
3061namespace sort_utils_detail {
3066inline constexpr long Median_Of_Three_Min_Size = 7;
3067
3084template <template <typename> class C, typename T, class Compare>
3085inline void median_of_three_to_last(C<T> &a, const long l, const long r, const Compare &cmp)
3086{
3087 if (r - l + 1 < Median_Of_Three_Min_Size)
3088 return;
3089 const long m = l + (r - l) / 2;
3090 if (cmp(a(m), a(l)))
3091 std::swap(a(l), a(m));
3092 if (cmp(a(r), a(m)))
3093 std::swap(a(m), a(r));
3094 if (cmp(a(m), a(l)))
3095 std::swap(a(l), a(m));
3096 std::swap(a(m), a(r));
3097}
3098} // namespace sort_utils_detail
3099
3108template <typename T, class Compare, typename Container>
3109inline long partition_op_impl(Container &a, const long l, const long r, const Compare &cmp)
3110{
3111 if (l == r)
3112 return l;
3113
3114 long i = l - 1;
3115 long j = r;
3116
3117 // The median of three items to position r
3119
3120 // Now pivot value is at a(r) - use direct access instead of reference
3121 while (true)
3122 {
3123 while (cmp(a(++i), a(r)))
3124 ;
3125
3126 while (cmp(a(r), a(--j)))
3127 if (j == l)
3128 break;
3129
3130 if (i >= j)
3131 break;
3132
3133 std::swap(a(i), a(j));
3134 }
3135
3137 std::swap(a(i), a(r));
3138
3139 return i;
3140}
3141
3149template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3150inline long partition_op(DynArray<T> &a, const long l, const long r, const Compare &cmp = Compare())
3151{
3152 return partition_op_impl<T, Compare>(a, l, r, cmp);
3153}
3154
3162template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3163inline long partition_op(Array<T> &a, const long l, const long r, const Compare &cmp = Compare())
3164{
3165 return partition_op_impl<T, Compare>(a, l, r, cmp);
3166}
3167
3168template <typename Container, class Compare>
3169static inline void insertion_sort_range(Container &a, long l, long r, const Compare &cmp)
3170{
3171 using T = typename Container::Item_Type;
3172 for (long p = l + 1; p <= r; ++p)
3173 {
3174 T key = std::move(a(p));
3175 long j = p - 1;
3176 while (j >= l and cmp(key, a(j)))
3177 {
3178 a(j + 1) = std::move(a(j));
3179 j--;
3180 }
3181 a(j + 1) = std::move(key);
3182 }
3183}
3184
3185template <typename T, class Compare>
3186static inline const T &__random_select(DynArray<T> &a, const long i, long l, long r,
3187 const Compare &cmp = Compare())
3188{
3189 assert(i >= l and i <= r);
3190
3191 while (l < r)
3192 {
3193 if (r - l < 10)
3194 {
3196 return a(i);
3197 }
3198
3199 const auto [lt, current] = partition_three_way_op<DynArray<T>, T, Compare>(a, l, r, cmp);
3200
3201 if (i >= lt and i <= current)
3202 return a(i);
3203
3204 if (i < lt)
3205 r = lt - 1;
3206 else
3207 l = current + 1;
3208 }
3209
3210 return a(l);
3211}
3212
3213template <typename T, class Compare>
3214static inline const T &__random_select(Array<T> &a, const long i, long l, long r,
3215 const Compare &cmp = Compare())
3216{
3217 assert(i >= l and i <= r);
3218
3219 while (l < r)
3220 {
3221 if (r - l < 10)
3222 {
3224 return a(i);
3225 }
3226
3227 const auto [lt, current] = partition_three_way_op<Array<T>, T, Compare>(a, l, r, cmp);
3228
3229 if (i >= lt and i <= current)
3230 return a(i);
3231
3232 if (i < lt)
3233 r = lt - 1;
3234 else
3235 l = current + 1;
3236 }
3237
3238 return a(l);
3239}
3240
3248template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3249const T &random_select(DynArray<T> &a, const long i, const Compare &cmp = Compare())
3250{
3251 const auto n_sz = a.size();
3252 ah_out_of_range_error_if(n_sz == 0 or i < 0) << "index out of range";
3253
3254 const long n = static_cast<long>(n_sz) - 1;
3255 ah_out_of_range_error_if(i > n) << "index out of range";
3256
3257 return __random_select<T, Compare>(a, i, 0, n, cmp);
3258}
3259
3267template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3268const T &random_select(Array<T> &a, const long i, const Compare &cmp = Compare())
3269{
3270 const auto n_sz = a.size();
3271 ah_out_of_range_error_if(n_sz == 0 or i < 0) << "index out of range";
3272
3273 const long n = static_cast<long>(n_sz) - 1;
3274 ah_out_of_range_error_if(i > n) << "index out of range";
3275
3276 return __random_select<T, Compare>(a, i, 0, n, cmp);
3277}
3278
3319template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3320const T &random_select(T *a, const long i, const long n, const Compare &cmp = Compare())
3321{
3322 ah_invalid_argument_if(a == nullptr and n > 0) << "null pointer";
3323
3324 ah_out_of_range_error_if(n <= 0 or i < 0 or i >= n) << "index out of range";
3325
3326 return __random_select<T, Compare>(a, i, 0, n - 1, cmp);
3327}
3328
3336template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3337const T &random_select(T *a, const long i, const long n, Compare &&cmp = Compare())
3338{
3339 return random_select<T, Compare>(a, i, n, cmp);
3340}
3341
3364template <class Compare>
3365Dlink *dlink_random_select(Dlink &list, const size_t i, const Compare &cmp = Compare())
3366{
3367 if (list.is_empty())
3368 return nullptr;
3369
3370 Dlink smaller; // list of minors than pivot
3371 Dlink bigger; // list of majors than pivot
3372
3373 size_t smaller_count = 0, // number of elements in smaller
3374 bigger_count = 0; // number of elements in bigger
3375
3376 Dlink *pivot = list.remove_next();
3377
3378 while (not list.is_empty())
3379 if (Dlink *p = list.remove_next(); cmp(p, pivot)) // p < pivot?
3380 {
3381 smaller.append(p);
3382 ++smaller_count;
3383 }
3384 else
3385 {
3386 bigger.append(p);
3387 ++bigger_count;
3388 }
3389
3390 if (i >= smaller_count + bigger_count + 1)
3391 {
3392 list.concat_list(&smaller);
3393 list.append(pivot);
3394 list.concat_list(&bigger);
3395 ah_out_of_range_error() << "index of selection greater than list's size";
3396 }
3397
3398 Dlink *ret_val = nullptr;
3399 if (i == smaller_count)
3400 ret_val = pivot;
3401 else if (i < smaller_count)
3402 ret_val = dlink_random_select<Compare>(smaller, i, cmp);
3403 else
3404 ret_val = dlink_random_select<Compare>(bigger, i - (smaller_count + 1), cmp);
3405
3406 list.concat_list(&smaller);
3407 list.append(pivot);
3408 list.concat_list(&bigger);
3409
3410 return ret_val;
3411}
3412
3438template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3439Dnode<T> *random_select(Dlink &list, const size_t i, const Compare &cmp = Compare())
3440{
3441 return static_cast<Dnode<T> *>(dlink_random_select<Compare_Dnode<T, Compare>>(list, i, cmp));
3442}
3443
3469template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3470T *random_select(DynDlist<T> &list, const size_t i, const Compare &cmp = Compare())
3471{
3472 Dlink *link = dlink_random_select<Compare_Dnode<T, Compare>>(list, i, cmp);
3473
3474 auto *p = static_cast<Dnode<T> *>(link);
3475
3476 return p != nullptr ? &(p->get_data()) : nullptr;
3477}
3478
3498template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3499inline void selection_sort(DynArray<T> &a, const Compare &cmp = Compare())
3500{
3501 const long n = static_cast<long>(a.size());
3502 if (n < 2)
3503 return;
3504
3505 for (long i = 0; i < n - 1; ++i)
3506 {
3507 long min = i;
3508
3509 for (long j = i + 1; j < n; ++j)
3510 if (cmp(a(j), a(min)))
3511 min = j;
3512
3513 if (cmp(a(min), a(i)))
3514 std::swap(a(min), a(i));
3515 }
3516}
3517
3548template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3549inline void bubble_sort(DynArray<T> &a, const Compare &cmp = Compare())
3550{
3551 const long n = static_cast<long>(a.size());
3552 if (n < 2)
3553 return;
3554
3555 for (long i = 0; i < n - 1; ++i)
3556 for (long j = n - 1; j > i; --j)
3557 if (cmp(a(j), a(j - 1)))
3559 std::swap(a(j - 1), a(j));
3560}
3561
3588template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3589inline void insertion_sort(C<T> &a, const long l, const long r, const Compare &cmp = Compare())
3590{
3591 for (long i = l + 1; i <= r; i++)
3592 {
3593 T tmp = std::move(a(i));
3594 long j = i;
3595 for (/* nothing */; j > l and cmp(tmp, a(j - 1)); --j)
3596 a(j) = std::move(a(j - 1));
3597
3598 a(j) = std::move(tmp);
3599 }
3600}
3601
3606template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3607inline void insertion_sort(C<T> &a, const Compare &cmp = Compare())
3608{
3609 const auto n = a.size();
3610 if (n <= 1)
3611 return;
3612 insertion_sort(a, 0, static_cast<long>(n) - 1, cmp);
3613}
3614
3649template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3650inline void shellsort(DynArray<T> &a, const Compare &cmp = Compare())
3651{
3652 const long n = a.size();
3653 if (n <= 1)
3654 return;
3655
3656 // Ciura's gap sequence - empirically optimal for most data distributions
3657 // Extended with ~2.25x multiplier for larger arrays
3658 static constexpr long ciura_gaps[] = {1, 4, 10, 23, 57, 132,
3659 301, 701, 1750, 4024, 9233, 21223,
3660 48805, 112217, 258100, 593630, 1365513, 3140680};
3661 static constexpr int num_gaps = std::size(ciura_gaps);
3662
3663 // Find the first gap smaller than the array size
3664 int gap_idx = num_gaps - 1;
3665 while (gap_idx >= 0 && ciura_gaps[gap_idx] >= n)
3666 --gap_idx;
3667
3668 // Sort with decreasing gaps
3669 for (; gap_idx >= 0; --gap_idx)
3670 {
3671 const long h = ciura_gaps[gap_idx];
3672 for (long i = h; i < n; i++)
3673 {
3674 T tmp = std::move(a(i));
3675 long j = i;
3676
3677 while (j >= h and cmp(tmp, a(j - h)))
3678 {
3679 a(j) = std::move(a(j - h));
3680 j -= h;
3681 }
3682
3683 a(j) = std::move(tmp);
3684 }
3685 }
3686}
3687
3689inline static long back_index(const long i) noexcept
3690{
3691 return i - 1;
3692}
3693
3700template <typename T, class Compare>
3701inline void sift_up(DynArray<T> &table, const long n, const Compare &cmp)
3702{
3703 long p;
3704 for (long i = n; i > 1; i = p)
3705 {
3706 p = i >> 1; // c = i/2
3707
3708 if (cmp(table(back_index(p)), table(back_index(i))))
3709 return;
3710
3711 std::swap(table(back_index(p)), table(back_index(i)));
3712 }
3713}
3714
3722template <typename T, class Compare>
3723inline void sift_down(DynArray<T> &table, const long start, const long n, const Compare &cmp)
3724{
3725 long i = start;
3726
3727 while (true)
3728 {
3729 long c = i << 1; // c = 2*i (left child)
3730
3731 if (c > n)
3732 return;
3733
3734 // Select the smaller/larger child depending on comparator
3735 if (c + 1 <= n)
3736 if (cmp(table(back_index(c + 1)), table(back_index(c))))
3737 c++;
3738
3739 if (cmp(table(back_index(i)), table(back_index(c))))
3740 return;
3741
3742 std::swap(table(back_index(c)), table(back_index(i)));
3743 i = c;
3744 }
3745}
3746
3748template <typename T, class Compare>
3749inline void sift_down(DynArray<T> &table, const long n, const Compare &cmp)
3750{
3751 sift_down<T, Compare>(table, 1, n, cmp);
3752}
3753
3766template <typename T, class Compare>
3768{
3769 Compare cmp;
3770
3771public:
3773 Negate_Compare(Compare __cmp = Compare()) noexcept(std::is_nothrow_copy_assignable_v<Compare>)
3774 : cmp(__cmp)
3775 { /* Empty */
3776 }
3777
3779 bool operator () (const T &e1, const T &e2) const
3780 noexcept(noexcept(static_cast<bool>(std::declval<const Compare &>()(e2, e1))))
3781 {
3782 return static_cast<bool>(cmp(e2, e1));
3783 }
3784};
3785
3826template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3827inline void heapsort(DynArray<T> &a, const Compare &cmp = Compare())
3828{
3829 const long n = a.size();
3830 if (n <= 1)
3831 return;
3832
3834
3835 // Floyd's heap construction: O(n) instead of O(n log n)
3836 // Start from the last non-leaf node and sift down each node
3837 for (long i = n / 2; i >= 1; --i)
3838 sift_down<T, Negate_Compare<T, Compare>>(a, i, n, nc);
3839
3840 // Extract elements from the heap one by one
3841 for (long i = n; i >= 2; --i)
3842 {
3843 std::swap(a(0), a(i - 1));
3844 sift_down<T, Negate_Compare<T, Compare>>(a, 1, i - 1, nc);
3845 }
3846}
3847
3856template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3857inline long partition(C<T> &a, const long l, const long r, const Compare &cmp = Compare())
3858{
3859 if (l == r)
3860 return l;
3861
3862 long i = l - 1;
3863 long j = r;
3864 const T &pivot = a(r);
3865
3866 while (true)
3867 {
3868 while (cmp(a(++i), pivot))
3869 ; /* Nothing else */
3870
3871 while (cmp(pivot, a(--j)))
3872 if (j == l)
3873 break;
3874
3875 if (i >= j)
3876 break;
3877
3878 std::swap(a(i), a(j));
3879 }
3880
3881 std::swap(a(i), a(r));
3882
3883 return i;
3884}
3885
3896template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3897inline void quicksort_rec(DynArray<T> &a, const long l, const long r, const Compare &cmp = Compare())
3898{
3899 if (r <= l)
3900 return;
3901
3903 if (const long i = partition(a, l, r, cmp); i - l < r - i)
3904 {
3905 quicksort_rec<T, Compare>(a, l, i - 1, cmp);
3906 quicksort_rec<T, Compare>(a, i + 1, r, cmp);
3907 }
3908 else
3909 {
3910 quicksort_rec<T, Compare>(a, i + 1, r, cmp);
3911 quicksort_rec<T, Compare>(a, l, i - 1, cmp);
3912 }
3913}
3914
3926template <class Stack, class A, class B>
3927inline void push2(Stack &stack, const A &a, const B &b)
3928{
3929 stack.push(b);
3930 stack.push(a);
3931}
3932
3964template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
3965inline void quicksort(DynArray<T> &a, const Compare &cmp = Compare())
3966{
3967 long l = 0, r = a.size() - 1;
3968
3969 const size_t n = a.size();
3971 FixedStack<long> stack((introsort_depth_limit(n) + 2) * 2);
3972
3973 push2(stack, l, r);
3974
3975 while (not stack.is_empty())
3976 {
3977 l = stack.pop();
3978 r = stack.pop();
3979
3980 if (r <= l)
3981 continue;
3982
3984 if (const long i = partition(a, l, r, cmp); i - l > r - i)
3985 {
3986 push2(stack, l, i - 1);
3987 push2(stack, i + 1, r);
3988 }
3989 else
3990 {
3991 push2(stack, i + 1, r);
3992 push2(stack, l, i - 1);
3993 }
3994 }
3995}
3996
4006template <typename T, class Compare>
4007inline void sift_down_subrange(DynArray<T> &a, long start, const long n, const long offset,
4008 const Compare &cmp)
4009{
4010 while (true)
4011 {
4012 long c = start << 1; // c = 2*start (left child)
4013 if (c > n)
4014 return;
4015
4016 // Select the child with higher priority
4017 if (c + 1 <= n)
4018 if (cmp(a(offset + c), a(offset + c - 1)))
4019 c++;
4020
4021 if (cmp(a(offset + start - 1), a(offset + c - 1)))
4022 return;
4023
4024 std::swap(a(offset + start - 1), a(offset + c - 1));
4025 start = c;
4026 }
4027}
4028
4045template <typename T, class Compare>
4046inline void heapsort_subrange(DynArray<T> &a, const long l, const long r, const Compare &cmp)
4047{
4048 const long n = r - l + 1;
4049 if (n <= 1)
4050 return;
4051
4053
4054 // Floyd's heap construction: O(n)
4055 for (long i = n / 2; i >= 1; --i)
4057
4058 // Extract elements
4059 for (long i = n; i >= 2; --i)
4060 {
4061 std::swap(a(l), a(l + i - 1));
4062 sift_down_subrange<T, Negate_Compare<T, Compare>>(a, 1, i - 1, l, nc);
4063 }
4064}
4065
4070template <typename T, class Compare>
4071void introsort_loop(DynArray<T> &a, long l, long r, size_t depth_limit, const Compare &cmp)
4072{
4073 while (r - l >= static_cast<long>(Quicksort_Threshold))
4074 {
4075 if (depth_limit == 0) [[unlikely]]
4076 {
4077 // Depth limit reached: switch to heapsort for guaranteed O(n log n)
4078 heapsort_subrange<T, Compare>(a, l, r, cmp);
4079 return;
4080 }
4081
4082 --depth_limit;
4083
4084 // The median of three items as the pivot: with the last item alone, a
4085 // sorted or a reversed range exhausted the depth limit
4087
4088 // Recurse on smaller partition, iterate on larger (tail call elimination)
4089 if (const long pivot = partition(a, l, r, cmp); pivot - l < r - pivot)
4090 {
4091 introsort_loop<T, Compare>(a, l, pivot - 1, depth_limit, cmp);
4092 l = pivot + 1;
4093 }
4094 else
4095 {
4096 introsort_loop<T, Compare>(a, pivot + 1, r, depth_limit, cmp);
4097 r = pivot - 1;
4098 }
4099 }
4100}
4101
4135template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4136inline void introsort(DynArray<T> &a, const Compare &cmp = Compare())
4137{
4138 const long n = a.size();
4139 if (n <= 1)
4140 return;
4141
4142 if (n < static_cast<long>(Quicksort_Threshold))
4143 {
4144 insertion_sort(a, 0, n - 1, cmp);
4145 return;
4146 }
4147
4149 introsort_loop<T, Compare>(a, 0, n - 1, introsort_depth_limit(n), cmp);
4150
4151 // Final insertion sort pass for small unsorted subarrays
4152 insertion_sort(a, 0, n - 1, cmp);
4153}
4154
4169template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4170inline long search_extreme(const DynArray<T> &a, const long l, const long r,
4171 const Compare &cmp = Compare())
4172{
4173 long extreme_index = l;
4174
4175 for (long i = l + 1; i <= r; i++)
4176 if (cmp(a(i), a(extreme_index)))
4177 extreme_index = i;
4178
4179 return extreme_index;
4180}
4181
4186template <typename T, StrictWeakOrder<T> Compare = Aleph::greater<T>>
4187inline long search_max(const DynArray<T> &a, const long l, const long r,
4188 const Compare &cmp = Compare())
4189{
4190 return search_extreme<T, Compare>(a, l, r, cmp);
4191}
4192
4238template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4239inline long binary_search(const C<T> &a, const T &x, long l, long r, const Compare &cmp = Compare())
4240{
4241 if (l > r)
4242 return l;
4243
4244 while (l <= r)
4245 if (long m = l + (r - l) / 2; cmp(x, a(m)))
4246 r = m - 1;
4247 else if (cmp(a(m), x))
4248 l = m + 1;
4249 else
4250 return m; // key found
4251
4252 return l;
4253}
4254
4272template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4273inline long binary_search(const C<T *> &a, const T &x, long l, long r, const Compare &cmp = Compare())
4274{
4275 if (l > r)
4276 return l;
4277
4278 while (l <= r)
4279 if (long m = l + (r - l) / 2; cmp(x, *a(m)))
4280 r = m - 1;
4281 else if (cmp(*a(m), x))
4282 l = m + 1;
4283 else
4284 return m; // found key
4285
4286 return l;
4287}
4288
4300template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4301inline long binary_search(const C<T *> &a, const T &x, Compare &&cmp = Compare())
4302{
4303 const auto n = a.size();
4304 if (n == 0)
4305 return 0;
4306
4307 return binary_search(a, x, 0, static_cast<long>(n) - 1, cmp);
4308}
4309
4336template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4337inline long binary_search(const C<T> &a, const T &x, const Compare &cmp = Compare())
4338{
4339 const auto n = a.size();
4340 if (n == 0)
4341 return 0;
4342
4343 return binary_search(a, x, 0, static_cast<long>(n) - 1, cmp);
4344}
4345
4359template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4360inline DynList<size_t> binary_search_dup(const C<T> &a, const T &x, const Compare &cmp = Compare())
4361{
4362 DynList<size_t> ret;
4363 const auto n = a.size();
4364 if (n == 0)
4365 return ret;
4366
4367 long idx = binary_search(a, x, 0, static_cast<long>(n) - 1, cmp);
4368 if (idx < 0)
4369 return ret;
4370
4371 if (not are_equals(a(idx), x, cmp))
4372 return ret;
4373
4374 ret.append(idx);
4375 for (long i = idx - 1; i >= 0; --i)
4376 {
4377 if (not are_equals(a(i), x, cmp))
4378 break;
4379 ret.insert(i);
4380 }
4381
4382 for (long i = idx + 1; i < static_cast<long>(n); ++i)
4383 {
4384 if (not are_equals(a(i), x, cmp))
4385 break;
4386 ret.append(i);
4387 }
4388
4389 return ret;
4390}
4391
4412template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4413inline Array<const T *> build_index_ptr(const C<T> &a, const Compare &cmp = Compare())
4414{
4415 const size_t n = a.size();
4417 for (size_t i = 0; i < n; ++i)
4418 ret(i) = &a(i);
4419
4420 quicksort_op(ret, [&cmp](const T *ptr1, const T *ptr2)
4421 {
4422 return cmp(*ptr1, *ptr2);
4423 });
4424
4425 return ret;
4426}
4427
4442template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4443inline DynList<const T *> bsearch_dup(const C<T> &a, const T &x, const Compare &cmp = Compare())
4444{
4446 long idx = binary_search(a, x, cmp);
4447 if (idx < 0)
4448 return ret;
4449
4450 const T *found_ptr = &a(idx);
4451 if (not are_equals(*found_ptr, x, cmp))
4452 return ret;
4453
4454 for (long i = idx - 1; i >= 0; --i)
4455 {
4456 const T *ptr = &a(i);
4457 if (not are_equals(*ptr, x, cmp))
4458 break;
4459 ret.insert(ptr);
4460 }
4461
4462 ret.append(found_ptr);
4463
4464 for (long i = idx + 1, n = a.size(); i < n; ++i)
4465 {
4466 const T *ptr = &a(i);
4467 if (not are_equals(*ptr, x, cmp))
4468 break;
4469 ret.append(ptr);
4470 }
4471
4472 return ret;
4473}
4474
4486template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4487inline T *bsearch(C<T> &a, const T &x, const Compare &cmp = Compare())
4488{
4489 long i = binary_search(a, x, cmp);
4490 if (i < 0)
4491 return nullptr;
4492 T *ptr = &a(i);
4493 return are_equals(*ptr, x, cmp) ? ptr : nullptr;
4494}
4495
4497template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4498inline const T *bsearch(const C<T> &a, const T &x, const Compare &cmp = Compare())
4499{
4500 long i = binary_search(a, x, cmp);
4501 if (i < 0)
4502 return nullptr;
4503 const T *ptr = &a(i);
4504 return are_equals(*ptr, x, cmp) ? ptr : nullptr;
4505}
4506
4518template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4519inline T *bsearch(const C<T *> &a, const T &x, const Compare &cmp = Compare())
4520{
4521 long i = binary_search(a, x, cmp);
4522 if (i < 0)
4523 return nullptr;
4524 T *ptr = a(i);
4525 return are_equals(*ptr, x, cmp) ? ptr : nullptr;
4526}
4527
4539template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4540inline DynList<T *> bsearch_dup(C<T> &a, const T &x, const Compare &cmp = Compare())
4541{
4542 DynList<T *> ret;
4543 long idx = binary_search(a, x, cmp);
4544 if (idx < 0)
4545 return ret;
4546
4547 T *found_ptr = &a(idx);
4548 if (not are_equals(*found_ptr, x, cmp))
4549 return ret;
4550
4551 for (long i = idx - 1; i >= 0; --i)
4552 {
4553 T *ptr = &a(i);
4554 if (not are_equals(*ptr, x, cmp))
4555 break;
4556 ret.insert(ptr);
4557 }
4558
4559 ret.append(found_ptr);
4560
4561 for (long i = idx + 1, n = a.size(); i < n; ++i)
4562 {
4563 T *ptr = &a(i);
4564 if (not are_equals(*ptr, x, cmp))
4565 break;
4566 ret.append(ptr);
4567 }
4568
4569 return ret;
4570}
4571
4583template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4584inline DynList<T *> bsearch_dup(const C<T *> &a, const T &x, const Compare &cmp = Compare())
4585{
4586 DynList<T *> ret;
4587 const auto n = a.size();
4588 if (n == 0)
4589 return ret;
4590
4591 long idx = binary_search(a, x, 0, static_cast<long>(n) - 1, cmp);
4592 if (idx < 0)
4593 return ret;
4594
4595 T *found_ptr = a(idx);
4596 if (not are_equals(*found_ptr, x, cmp))
4597 return ret;
4598
4599 for (long i = idx - 1; i >= 0; --i)
4600 {
4601 T *ptr = a(i);
4602 if (not are_equals(*ptr, x, cmp))
4603 break;
4604 ret.insert(ptr);
4605 }
4606
4607 ret.append(found_ptr);
4608
4609 for (long i = idx + 1, n = a.size(); i < n; ++i)
4610 {
4611 T *ptr = a(i);
4612 if (not are_equals(*ptr, x, cmp))
4613 break;
4614 ret.append(ptr);
4615 }
4616
4617 return ret;
4618}
4619
4653template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4654inline long binindex(const C<T> &a, const T &x, const Compare &cmp = Compare())
4655{
4656 return binary_search(a, x, cmp);
4657}
4658
4688template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4689inline DynList<long> binindex_dup(const C<T> &a, const T &x, const Compare &cmp = Compare())
4690{
4691 DynList<long> ret;
4692 long idx = binary_search(a, x, cmp);
4693 if (idx < 0)
4694 return ret;
4695
4696 if (not are_equals(a(idx), x, cmp))
4697 return ret;
4698
4699 const long mid = idx;
4700
4701 for (long i = idx - 1; i >= 0; --i)
4702 {
4703 if (not are_equals(a(i), x, cmp))
4704 break;
4705 ret.insert(i);
4706 }
4707
4708 ret.append(mid);
4709
4710 for (long i = idx + 1, n = a.size(); i < n; ++i)
4711 {
4712 if (not are_equals(a(i), x, cmp))
4713 break;
4714 ret.append(i);
4715 }
4716
4717 return ret;
4718}
4719
4731template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4732inline DynList<long> binindex_dup(const C<T *> &a, const T &x, const Compare &cmp = Compare())
4733{
4734 DynList<long> ret;
4735 long idx = binary_search(a, x, cmp);
4736 if (idx < 0)
4737 return ret;
4738
4739 T *ptr = a(idx);
4740 if (not are_equals(*ptr, x, cmp))
4741 return ret;
4742
4743 for (long i = idx - 1; i >= 0; --i)
4744 {
4745 ptr = a(i);
4746 if (not are_equals(*ptr, x, cmp))
4747 break;
4748 ret.insert(i);
4749 }
4750
4751 ret.append(idx);
4752
4753 for (long i = idx + 1, n = a.size(); i < n; ++i)
4754 {
4755 T *ptr = a(i);
4756 if (not are_equals(*ptr, x, cmp))
4757 break;
4758 ret.append(i);
4759 }
4760
4761 return ret;
4762}
4763
4765
4772namespace sort_utils_detail {
4785template <class C>
4786decltype(auto) indexed_value(const C &c, const size_t i)
4787{
4788 if constexpr (requires { c(i); })
4789 return c(i);
4790 else
4791 return c[i];
4792}
4793
4802template <class C>
4803using Indexed_Value_Type =
4804 std::remove_cvref_t<decltype(indexed_value(std::declval<const C &>(), size_t{}))>;
4805
4821template <class C, class Compare>
4822bool stable_index_less(const C &c, const size_t i, const size_t j, const Compare &cmp)
4823{
4824 auto &&lhs = indexed_value(c, i);
4825 auto &&rhs = indexed_value(c, j);
4826
4827 if (cmp(lhs, rhs))
4828 return true;
4829
4830 if (cmp(rhs, lhs))
4831 return false;
4832
4833 return i < j;
4834}
4835} // namespace sort_utils_detail
4837
4882template <class C,
4883 StrictWeakOrder<sort_utils_detail::Indexed_Value_Type<C>> Compare =
4885inline Array<size_t> build_index(const C &a, const Compare &cmp = Compare())
4886{
4887 const size_t n = a.size();
4889 for (size_t i = 0; i < n; ++i)
4890 ret(i) = i;
4891
4892 quicksort_op(ret, [&a, &cmp](const size_t i, const size_t j)
4893 {
4894 return cmp(sort_utils_detail::indexed_value(a, i), sort_utils_detail::indexed_value(a, j));
4895 });
4896
4897 return ret;
4898}
4899
4939template <class C,
4940 StrictWeakOrder<sort_utils_detail::Indexed_Value_Type<C>> Compare =
4942inline Array<size_t> stable_build_index(const C &a, const Compare &cmp = Compare())
4943{
4944 const size_t n = a.size();
4946 for (size_t i = 0; i < n; ++i)
4947 ret(i) = i;
4948
4949 quicksort_op(ret, [&a, &cmp](const size_t i, const size_t j)
4950 {
4951 return sort_utils_detail::stable_index_less(a, i, j, cmp);
4952 });
4953
4954 return ret;
4955}
4956
4989template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
4990inline Array<T *> build_index_ptr(C<T> &a, const Compare &cmp = Compare())
4991{
4992 const size_t n = a.size();
4994 for (size_t i = 0; i < n; ++i)
4995 ret(i) = &a(i);
4996
4997 quicksort_op(ret, [&cmp](const T *ptr1, const T *ptr2)
4998 {
4999 return cmp(*ptr1, *ptr2);
5000 });
5001
5002 return ret;
5003}
5004
5033template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
5034inline Array<const T *> stable_build_index_ptr(const C<T> &a, const Compare &cmp = Compare())
5035{
5036 const size_t n = a.size();
5038 for (size_t i = 0; i < n; ++i)
5039 idx(i) = i;
5040
5041 quicksort_op(idx, [&a, &cmp](const size_t i, const size_t j)
5042 {
5043 return sort_utils_detail::stable_index_less(a, i, j, cmp);
5044 });
5045
5047 for (size_t i = 0; i < n; ++i)
5048 ret(i) = &a(idx(i));
5049
5050 return ret;
5051}
5052
5071template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
5072inline Array<T *> stable_build_index_ptr(C<T> &a, const Compare &cmp = Compare())
5073{
5074 const size_t n = a.size();
5076 for (size_t i = 0; i < n; ++i)
5077 idx(i) = i;
5078
5079 quicksort_op(idx, [&a, &cmp](const size_t i, const size_t j)
5080 {
5081 return sort_utils_detail::stable_index_less(a, i, j, cmp);
5082 });
5083
5085 for (size_t i = 0; i < n; ++i)
5086 ret(i) = &a(idx(i));
5087
5088 return ret;
5089}
5090
5118template <template <typename> class C, typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
5119inline void quicksort_op(C<T> &a, const Compare &cmp = Compare(),
5120 const size_t threshold = Quicksort_Threshold)
5121{
5122 const size_t n = a.size();
5123 if (n <= 1)
5124 return;
5125
5126 size_t l = 0, r = n - 1;
5127
5128 FixedStack<size_t> stack((introsort_depth_limit(n) + 2) * 2);
5129
5130 push2(stack, l, r);
5131
5132 while (not stack.is_empty())
5133 {
5134 l = stack.pop();
5135 r = stack.pop();
5136
5137 const size_t partition_size = r - l + 1;
5138 if (partition_size <= 1)
5139 continue;
5140
5141 if (partition_size <= threshold)
5142 {
5143 insertion_sort(a, l, r, cmp);
5144 continue;
5145 }
5146
5147 const auto i = static_cast<size_t>(
5148 partition_op<T, Compare>(a, static_cast<long>(l), static_cast<long>(r), cmp));
5149
5150 const size_t left_size = i > l ? i - l : 0;
5151 const size_t right_size = r > i ? r - i : 0;
5152
5153 if (left_size > right_size)
5154 {
5155 if (left_size > 0)
5156 push2(stack, l, i - 1);
5157 if (right_size > 0)
5158 push2(stack, i + 1, r);
5159 }
5160 else
5161 {
5162 if (right_size > 0)
5163 push2(stack, i + 1, r);
5164 if (left_size > 0)
5165 push2(stack, l, i - 1);
5166 }
5167 }
5168}
5169
5178template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
5179inline long binary_search_rec(T *a, const T &x, const long l, const long r,
5180 const Compare &cmp = Compare())
5181{
5182 if (l > r)
5183 return l;
5184
5185 const long m = l + (r - l) / 2;
5186
5187 if (cmp(x, a[m]))
5188 return binary_search_rec<T, Compare>(a, x, l, m - 1, cmp);
5189 if (cmp(a[m], x))
5190 return binary_search_rec<T, Compare>(a, x, m + 1, r, cmp);
5191
5192 return m;
5193}
5194
5203template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
5204inline long binary_search(T *a, const T &x, long l, long r, const Compare &cmp = Compare())
5205{
5206 while (l <= r)
5207 {
5208 long m = l + (r - l) / 2;
5209 if (cmp(x, a[m]))
5210 r = m - 1;
5211 else if (cmp(a[m], x))
5212 l = m + 1;
5213 else
5214 return m;
5215 }
5216 return l;
5217}
5218
5245template <typename KeyFn>
5246 requires std::invocable<const KeyFn &, size_t> and
5247 std::convertible_to<std::invoke_result_t<const KeyFn &, size_t>, int>
5248void counting_sort_indices(Array<size_t> &sa, Array<size_t> &tmp, const size_t n, const int min_key,
5249 const int max_key, const KeyFn &key_of)
5250{
5251 ah_domain_error_if(max_key < min_key) << "counting_sort_indices(): max_key < min_key";
5252
5253 if (n == 0)
5254 return;
5255
5256 ah_out_of_range_error_if(sa.size() < n or tmp.size() < n)
5257 << "counting_sort_indices(): sa/tmp size is smaller than n";
5258
5259 const auto range_minus_one = static_cast<unsigned long long>(static_cast<long long>(max_key) -
5260 static_cast<long long>(min_key));
5262 constexpr auto max_count =
5263 static_cast<unsigned long long>(std::numeric_limits<size_t>::max() - size_t(1));
5264 ah_runtime_error_unless(range_minus_one <= max_count)
5265 << "counting_sort_indices(): key range is too large";
5266
5267 const auto k = static_cast<size_t>(range_minus_one) + 1;
5269 for (size_t i = 0; i < k; ++i)
5270 count[i] = 0;
5271
5272 for (size_t i = 0; i < n; ++i)
5273 {
5274 const int key = key_of(sa[i]);
5275 ah_out_of_range_error_if(key < min_key or key > max_key)
5276 << "counting_sort_indices(): key out of expected range";
5277 const auto bucket = static_cast<size_t>(static_cast<unsigned long long>(
5278 static_cast<long long>(key) - static_cast<long long>(min_key)));
5279 ++count[bucket];
5280 }
5281
5282 for (size_t j = 1; j < k; ++j)
5283 count[j] += count[j - 1];
5284
5285 for (size_t i = n; i > 0; --i)
5286 {
5287 const int key = key_of(sa[i - 1]);
5288 const auto idx = static_cast<size_t>(static_cast<unsigned long long>(
5289 static_cast<long long>(key) - static_cast<long long>(min_key)));
5290 tmp[--count[idx]] = sa[i - 1];
5291 }
5292
5293 for (size_t i = 0; i < n; ++i)
5294 sa[i] = tmp[i];
5295}
5296
5297namespace sort_utils_detail {
5306template <typename IntT>
5307using counting_unsigned_t = std::make_unsigned_t<std::remove_cv_t<IntT>>;
5308
5317template <typename IntT>
5318using radix_unsigned_t = std::make_unsigned_t<std::remove_cv_t<IntT>>;
5319
5329template <typename IntT>
5330[[nodiscard]] size_t counting_bucket_count(const IntT min_key, const IntT max_key)
5331{
5332 ah_domain_error_if(max_key < min_key) << "counting_sort(): max_key < min_key";
5333
5334 using U = counting_unsigned_t<IntT>;
5335 const U range_minus_one = static_cast<U>(max_key) - static_cast<U>(min_key);
5336
5337 if constexpr (sizeof(U) >= sizeof(size_t))
5338 {
5339 constexpr size_t max_count = std::numeric_limits<size_t>::max() - static_cast<size_t>(1);
5340 ah_runtime_error_unless(range_minus_one <= static_cast<U>(max_count))
5341 << "counting_sort(): key range is too large";
5342 }
5343
5344 return static_cast<size_t>(range_minus_one) + 1;
5345}
5346
5354template <typename IntT>
5355[[nodiscard]] inline size_t counting_bucket(const IntT value, const IntT min_key) noexcept
5356{
5357 return static_cast<size_t>(static_cast<counting_unsigned_t<IntT>>(value) -
5358 static_cast<counting_unsigned_t<IntT>>(min_key));
5359}
5360
5368template <typename IntT>
5369[[nodiscard]] inline IntT counting_value_from_bucket(const size_t bucket, const IntT min_key) noexcept
5370{
5371 using U = counting_unsigned_t<IntT>;
5372 return static_cast<IntT>(static_cast<U>(min_key) + static_cast<U>(bucket));
5373}
5374
5381template <template <typename> class C, typename IntT>
5383void counting_sort_impl(C<IntT> &a)
5384{
5385 const size_t n = a.size();
5386 if (n < 2)
5387 return;
5388
5389 IntT min_key = a(0), max_key = a(0);
5390 for (size_t i = 1; i < n; ++i)
5391 {
5392 if (a(i) < min_key)
5393 min_key = a(i);
5394 if (a(i) > max_key)
5395 max_key = a(i);
5396 }
5397
5398 const size_t k = counting_bucket_count(min_key, max_key);
5400 for (size_t i = 0; i < k; ++i)
5401 count[i] = 0;
5402
5403 for (size_t i = 0; i < n; ++i)
5404 ++count[counting_bucket(a(i), min_key)];
5405
5406 for (size_t i = 1; i < k; ++i)
5407 count[i] += count[i - 1];
5408
5410 for (size_t i = n; i > 0; --i)
5411 {
5412 const auto bucket = counting_bucket(a(i - 1), min_key);
5413 tmp[--count[bucket]] = a(i - 1);
5414 }
5415
5416 for (size_t i = 0; i < n; ++i)
5417 a(i) = tmp[i];
5418}
5419
5429template <typename IntT>
5431void counting_sort_impl(IntT *a, const size_t n)
5432{
5433 if (n < 2)
5434 return;
5435
5436 IntT min_key = a[0], max_key = a[0];
5437 for (size_t i = 1; i < n; ++i)
5438 {
5439 if (a[i] < min_key)
5440 min_key = a[i];
5441 if (a[i] > max_key)
5442 max_key = a[i];
5443 }
5444
5445 const size_t k = counting_bucket_count(min_key, max_key);
5447 for (size_t i = 0; i < k; ++i)
5448 count[i] = 0;
5449
5450 for (size_t i = 0; i < n; ++i)
5451 ++count[counting_bucket(a[i], min_key)];
5452
5453 for (size_t i = 1; i < k; ++i)
5454 count[i] += count[i - 1];
5455
5457 for (size_t i = n; i > 0; --i)
5458 {
5459 const auto bucket = counting_bucket(a[i - 1], min_key);
5460 tmp[--count[bucket]] = a[i - 1];
5461 }
5462
5463 for (size_t i = 0; i < n; ++i)
5464 a[i] = tmp[i];
5465}
5466
5475template <typename IntT>
5478{
5479 const size_t n = list.size();
5480 if (n < 2)
5481 return;
5482
5483 typename DynList<IntT>::Iterator it(list);
5484 IntT min_key = it.get_curr_ne();
5485 IntT max_key = min_key;
5486 for (it.next_ne(); it.has_curr(); it.next_ne())
5487 {
5488 const IntT value = it.get_curr_ne();
5489 if (value < min_key)
5490 min_key = value;
5491 if (value > max_key)
5492 max_key = value;
5493 }
5494
5495 const size_t k = counting_bucket_count(min_key, max_key);
5497 for (size_t i = 0; i < k; ++i)
5498 count[i] = 0;
5499
5500 for (typename DynList<IntT>::Iterator scan(list); scan.has_curr(); scan.next_ne())
5501 ++count[counting_bucket(scan.get_curr_ne(), min_key)];
5502
5503 typename DynList<IntT>::Iterator out(list);
5504 for (size_t bucket = 0; bucket < k; ++bucket)
5505 {
5506 const size_t times = count[bucket];
5507 if (times == 0)
5508 continue;
5509
5510 const IntT value = counting_value_from_bucket(bucket, min_key);
5511 for (size_t c = 0; c < times; ++c)
5512 {
5513 out.get_curr_ne() = value;
5514 out.next_ne();
5515 }
5516 }
5517}
5518
5527template <typename IntT>
5530{
5531 const size_t n = list.size();
5532 if (n < 2)
5533 return;
5534
5535 typename DynDlist<IntT>::Iterator it(list);
5536 IntT min_key = it.get_curr_ne();
5537 IntT max_key = min_key;
5538 for (it.next_ne(); it.has_curr(); it.next_ne())
5539 {
5540 const IntT value = it.get_curr_ne();
5541 if (value < min_key)
5542 min_key = value;
5543 if (value > max_key)
5544 max_key = value;
5545 }
5546
5547 const size_t k = counting_bucket_count(min_key, max_key);
5549 for (size_t i = 0; i < k; ++i)
5550 count[i] = 0;
5551
5552 for (typename DynDlist<IntT>::Iterator scan(list); scan.has_curr(); scan.next_ne())
5553 ++count[counting_bucket(scan.get_curr_ne(), min_key)];
5554
5555 typename DynDlist<IntT>::Iterator out(list);
5556 for (size_t bucket = 0; bucket < k; ++bucket)
5557 {
5558 const size_t times = count[bucket];
5559 if (times == 0)
5560 continue;
5561
5562 const IntT value = counting_value_from_bucket(bucket, min_key);
5563 for (size_t c = 0; c < times; ++c)
5564 {
5565 out.get_curr_ne() = value;
5566 out.next_ne();
5567 }
5568 }
5569}
5570
5581template <typename IntT>
5582[[nodiscard]] constexpr radix_unsigned_t<IntT> radix_key(const IntT value) noexcept
5583{
5584 using U = radix_unsigned_t<IntT>;
5585 if constexpr (std::is_signed_v<std::remove_cv_t<IntT>>)
5586 return static_cast<U>(value) ^ (U{1} << (std::numeric_limits<U>::digits - 1));
5587 else
5588 return static_cast<U>(value);
5589}
5590
5600template <template <typename> class C, typename IntT>
5602void radix_sort_impl(C<IntT> &a)
5603{
5604 using U = radix_unsigned_t<IntT>;
5605
5606 const size_t n = a.size();
5607 if (n < 2)
5608 return;
5609
5612
5613 for (size_t pass = 0; pass < sizeof(U); ++pass)
5614 {
5615 for (size_t i = 0; i < 256; ++i)
5616 count[i] = 0;
5617
5618 const size_t shift = pass * 8;
5619 for (size_t i = 0; i < n; ++i)
5620 {
5621 const U key = radix_key<IntT>(a(i));
5622 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5623 ++count[bucket];
5624 }
5625
5626 for (size_t i = 1; i < 256; ++i)
5627 count[i] += count[i - 1];
5628
5629 for (size_t i = n; i > 0; --i)
5630 {
5631 const U key = radix_key<IntT>(a(i - 1));
5632 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5633 tmp[--count[bucket]] = a(i - 1);
5634 }
5635
5636 for (size_t i = 0; i < n; ++i)
5637 a(i) = tmp[i];
5638 }
5639}
5640
5649template <typename IntT>
5651void radix_sort_impl(IntT *a, const size_t n)
5652{
5653 using U = radix_unsigned_t<IntT>;
5654
5655 if (n < 2)
5656 return;
5657
5660
5661 for (size_t pass = 0; pass < sizeof(U); ++pass)
5662 {
5663 for (size_t i = 0; i < 256; ++i)
5664 count[i] = 0;
5665
5666 const size_t shift = pass * 8;
5667 for (size_t i = 0; i < n; ++i)
5668 {
5669 const U key = radix_key<IntT>(a[i]);
5670 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5671 ++count[bucket];
5672 }
5673
5674 for (size_t i = 1; i < 256; ++i)
5675 count[i] += count[i - 1];
5676
5677 for (size_t i = n; i > 0; --i)
5678 {
5679 const U key = radix_key<IntT>(a[i - 1]);
5680 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5681 tmp[--count[bucket]] = a[i - 1];
5682 }
5683
5684 for (size_t i = 0; i < n; ++i)
5685 a[i] = tmp[i];
5686 }
5687}
5688
5697template <typename IntT>
5700{
5701 using U = radix_unsigned_t<IntT>;
5702
5703 if (const size_t n = list.size(); n < 2)
5704 return;
5705
5706 Array<HTList> buckets;
5707 buckets.reserve(256);
5708 for (size_t i = 0; i < 256; ++i)
5709 buckets.append(HTList());
5710
5711 for (size_t pass = 0; pass < sizeof(U); ++pass)
5712 {
5713 const size_t shift = pass * 8;
5714
5715 while (not list.is_empty())
5716 {
5717 Slinknc *link = list.HTList::remove_first_ne();
5718 auto *node = static_cast<Snodenc<IntT> *>(link);
5719 const U key = radix_key<IntT>(node->get_data());
5720 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5721 buckets[bucket].append(link);
5722 }
5723
5724 for (auto &bucket : buckets)
5725 list.HTList::append(bucket);
5726 }
5727}
5728
5736template <typename IntT>
5739{
5740 using U = radix_unsigned_t<IntT>;
5741
5742 if (const size_t n = list.size(); n < 2)
5743 return;
5744
5745 Array<Dnode<IntT>> buckets;
5746 buckets.reserve(256);
5747 for (size_t i = 0; i < 256; ++i)
5748 buckets.append(Dnode<IntT>());
5749
5750 for (size_t pass = 0; pass < sizeof(U); ++pass)
5751 {
5752 const size_t shift = pass * 8;
5753
5754 while (not list.template Dnode<IntT>::is_empty())
5755 {
5756 Dnode<IntT> *node = list.template Dnode<IntT>::remove_first_ne();
5757 const U key = radix_key<IntT>(node->get_data());
5758 const auto bucket = static_cast<size_t>((key >> shift) & U{0xFF});
5759 buckets[bucket].append(node);
5760 }
5761
5762 for (auto &bucket : buckets)
5763 list.template Dnode<IntT>::append_list(&bucket);
5764 }
5765}
5766} // namespace sort_utils_detail
5767
5772template <typename T>
5774
5779template <typename T>
5781
5810template <typename T>
5811 requires CountingSortable<T>
5817
5833template <typename T>
5834 requires CountingSortable<T>
5840
5860template <typename T>
5861 requires CountingSortable<T>
5867
5887template <typename T>
5888 requires CountingSortable<T>
5894
5909template <typename T>
5910 requires CountingSortable<T>
5911void counting_sort(T *a, const size_t n)
5912{
5913 ah_invalid_argument_if(a == nullptr and n > 0)
5914 << "counting_sort(): null pointer with non-zero length";
5917}
5918
5928template <typename T, size_t N>
5929 requires CountingSortable<T>
5930void counting_sort(T (&a)[N])
5931{
5932 counting_sort(a, N);
5933}
5934
5965template <typename T>
5966 requires RadixSortable<T>
5972
5987template <typename T>
5988 requires RadixSortable<T>
5994
6005template <typename T>
6006 requires RadixSortable<T>
6012
6023template <typename T>
6024 requires RadixSortable<T>
6030
6043template <typename T>
6044 requires RadixSortable<T>
6045void radix_sort(T *a, const size_t n)
6046{
6047 ah_invalid_argument_if(a == nullptr and n > 0)
6048 << "radix_sort(): null pointer with non-zero length";
6051}
6052
6062template <typename T, size_t N>
6063 requires RadixSortable<T>
6064void radix_sort(T (&a)[N])
6065{
6066 radix_sort(a, N);
6067}
6068
6069// ================================================================
6070// Bucket Sort
6071// ================================================================
6072
6073namespace bucket_sort_detail {
6077template <typename T, class Compare>
6078void insertion_sort_range(T *a, const size_t lo, const size_t hi, const Compare &cmp) noexcept(
6079 std::is_nothrow_move_constructible_v<T> and std::is_nothrow_move_assignable_v<T> and
6080 noexcept(static_cast<bool>(std::declval<const Compare &>()(std::declval<T &>(),
6081 std::declval<T &>()))))
6082{
6083 for (size_t i = lo + 1; i < hi; ++i)
6084 {
6085 T tmp = std::move(a[i]);
6086 size_t j = i;
6087 while (j > lo and static_cast<bool>(cmp(tmp, a[j - 1])))
6088 {
6089 a[j] = std::move(a[j - 1]);
6090 --j;
6091 }
6092 a[j] = std::move(tmp);
6093 }
6094}
6095
6106template <typename T, class Compare, class BucketKey>
6107void bucket_sort_impl(T *a, const size_t n, const size_t num_buckets, const BucketKey &bucket_key,
6108 const Compare &cmp)
6109{
6110 if (n < 2)
6111 return;
6112
6113 ah_domain_error_if(num_buckets == 0) << "bucket_sort: num_buckets must be > 0";
6114
6115 // Count elements per bucket
6116 Array<size_t> counts = Array<size_t>::create(num_buckets);
6117 for (size_t i = 0; i < num_buckets; ++i)
6118 counts[i] = 0;
6119
6120 for (size_t i = 0; i < n; ++i)
6121 {
6122 const size_t b = bucket_key(a[i]);
6123 ah_domain_error_if(b >= num_buckets) << "bucket_sort: bucket_key returned " << b
6124 << " which is >= num_buckets (" << num_buckets << ")";
6125 ++counts[b];
6126 }
6127
6128 // Compute bucket start offsets (prefix sum)
6129 Array<size_t> offsets = Array<size_t>::create(num_buckets);
6130 offsets[0] = 0;
6131 for (size_t i = 1; i < num_buckets; ++i)
6132 offsets[i] = offsets[i - 1] + counts[i - 1];
6133
6134 // Distribute elements into a temporary array (stable)
6135 Array<T> tmp = Array<T>::create(n);
6136 // Reset counts for placement
6137 for (size_t i = 0; i < num_buckets; ++i)
6138 counts[i] = 0;
6139
6140 for (size_t i = 0; i < n; ++i)
6141 {
6142 const size_t b = bucket_key(a[i]);
6143 tmp[offsets[b] + counts[b]] = std::move(a[i]);
6144 ++counts[b];
6145 }
6146
6147 // Sort each bucket with insertion sort
6148 for (size_t b = 0; b < num_buckets; ++b)
6149 if (counts[b] > 1)
6150 insertion_sort_range(&tmp[0], offsets[b], offsets[b] + counts[b], cmp);
6151
6152 // Copy back
6153 for (size_t i = 0; i < n; ++i)
6154 a[i] = std::move(tmp[i]);
6155}
6156
6165template <typename T, class Container, class SortFn, class Compare>
6166void apply_sort_with_temp(Container &a, SortFn sort_fn, const Compare &cmp)
6167{
6168 const size_t n = a.size();
6169 if (n < 2)
6170 return;
6171
6172 Array<T> tmp = Array<T>::create(n);
6173 size_t i = 0;
6174 for (auto it = a.get_it(); it.has_curr(); it.next_ne())
6175 tmp[i++] = std::move(it.get_curr_ne());
6176
6177 sort_fn(&tmp[0], n, cmp);
6178
6179 i = 0;
6180 for (auto it = a.get_it(); it.has_curr(); it.next_ne())
6181 it.get_curr_ne() = std::move(tmp[i++]);
6182}
6183
6185template <auto SortFn>
6187{
6188 template <class Compare>
6189 auto operator () (const Compare &) const
6190 {
6191 return [](auto *p, size_t n, const Compare &c)
6192 {
6193 SortFn(p, n, c);
6194 };
6195 }
6196};
6197
6199template <class BucketKey>
6201{
6203 const BucketKey &bucket_key;
6204
6205 template <class Compare>
6206 auto operator () (const Compare &) const
6207 {
6208 return [this](auto *p, size_t n, const Compare &c)
6209 {
6211 };
6212 }
6213};
6214} // namespace bucket_sort_detail
6215
6264template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>, class BucketKey>
6265void bucket_sort(T *a, const size_t n, const size_t num_buckets, const BucketKey &bucket_key,
6266 const Compare &cmp = Compare())
6267{
6268 ah_invalid_argument_if(a == nullptr and n > 0)
6269 << "bucket_sort(): null pointer with non-zero length";
6271 bucket_sort_detail::bucket_sort_impl(a, n, num_buckets, bucket_key, cmp);
6272}
6273
6307template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
6308 requires std::floating_point<T>
6309void bucket_sort(T *a, const size_t n, const Compare &cmp = Compare())
6310{
6311 ah_invalid_argument_if(a == nullptr and n > 0)
6312 << "bucket_sort(): null pointer with non-zero length";
6313
6314 if (n < 2)
6315 return;
6316
6317 T min_val = a[0], max_val = a[0];
6318 for (size_t i = 0; i < n; ++i)
6319 {
6320 if (not std::isfinite(a[i])) [[unlikely]]
6321 {
6322 timsort(a, n, cmp);
6323 return;
6324 }
6325 if (a[i] < min_val)
6326 min_val = a[i];
6327 if (a[i] > max_val)
6328 max_val = a[i];
6329 }
6330
6331 const T range = max_val - min_val;
6332 if (range == T{0})
6333 return; // all equal
6334
6335 // Numeric interpolation is only correct for the default arithmetic
6336 // comparators (Aleph::less / Aleph::greater). For any other comparator
6337 // the mapping from value to bucket index is undefined, so fall back to
6338 // the stable timsort which respects the caller's comparator directly.
6339 if constexpr (std::is_same_v<Compare, Aleph::less<T>> or std::is_same_v<Compare, Aleph::greater<T>>)
6340 {
6341 const bool descending = cmp(max_val, min_val) and not cmp(min_val, max_val);
6342 const size_t num_buckets = n;
6343 auto key = [min_val, range, num_buckets, descending](const T &val) -> size_t
6344 {
6345 auto b = static_cast<size_t>((val - min_val) / range * static_cast<T>(num_buckets - 1));
6346 if (b >= num_buckets)
6347 b = num_buckets - 1;
6348
6349 if (descending)
6350 b = (num_buckets - 1) - b;
6351
6352 return b;
6353 };
6354
6355 bucket_sort_detail::bucket_sort_impl(a, n, num_buckets, key, cmp);
6356 }
6357 else
6358 {
6359 // Custom comparator: bucket interpolation is not order-preserving;
6360 // delegate to timsort which respects any strict-weak-ordering comparator.
6361 timsort(a, n, cmp);
6362 }
6363}
6364
6377template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
6378 requires std::floating_point<T>
6379void bucket_sort(DynArray<T> &a, const Compare &cmp = Compare())
6380{
6381 bucket_sort_detail::apply_sort_with_temp<T>(
6382 a,
6383 bucket_sort_detail::sort_invoker_factory<static_cast<void (*)(T *, size_t, const Compare &)>(
6384 bucket_sort)>{}(cmp),
6385 cmp);
6386}
6387
6397template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
6398 requires std::floating_point<T>
6399void bucket_sort(Array<T> &a, const Compare &cmp = Compare())
6400{
6401 if (a.size() < 2)
6402 return;
6403 bucket_sort(&a[0], a.size(), cmp);
6404}
6405
6416template <typename T, size_t N, StrictWeakOrder<T> Compare = Aleph::less<T>>
6417 requires std::floating_point<T>
6418void bucket_sort(T (&a)[N], const Compare &cmp = Compare())
6419{
6420 bucket_sort(static_cast<T *>(a), N, cmp);
6421}
6422
6435template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
6436 requires std::floating_point<T>
6437void bucket_sort(DynList<T> &list, const Compare &cmp = Compare())
6438{
6439 bucket_sort_detail::apply_sort_with_temp<T>(
6440 list,
6441 bucket_sort_detail::sort_invoker_factory<static_cast<void (*)(T *, size_t, const Compare &)>(
6442 bucket_sort)>{}(cmp),
6443 cmp);
6444}
6445
6458template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>, class BucketKey>
6459void bucket_sort(DynArray<T> &a, const size_t num_buckets, const BucketKey &bucket_key,
6460 const Compare &cmp = Compare())
6461{
6462 bucket_sort_detail::apply_sort_with_temp<T>(
6464}
6465
6478template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>, class BucketKey>
6479void bucket_sort(Array<T> &a, const size_t num_buckets, const BucketKey &bucket_key,
6480 const Compare &cmp = Compare())
6481{
6482 if (a.size() < 2)
6483 return;
6484 bucket_sort(&a[0], a.size(), num_buckets, bucket_key, cmp);
6485}
6486
6487// ================================================================
6488// Timsort
6489// ================================================================
6490
6491namespace timsort_detail {
6498[[nodiscard]] constexpr size_t compute_minrun(size_t n) noexcept
6499{
6500 size_t r = 0;
6501 while (n >= 64)
6502 {
6503 r |= n & 1;
6504 n >>= 1;
6505 }
6506 return n + r;
6507}
6508
6512template <typename T>
6513void reverse_range(T *a, size_t lo, size_t hi) noexcept(std::is_nothrow_swappable_v<T>)
6514{
6515 while (lo + 1 < hi)
6516 {
6517 std::swap(a[lo], a[hi - 1]);
6518 ++lo;
6519 --hi;
6520 }
6521}
6522
6531template <typename T, class Compare>
6532size_t count_run_and_make_ascending(T *a, const size_t lo, const size_t hi, const Compare &cmp)
6533{
6534 if (hi - lo <= 1)
6535 return hi - lo;
6536
6537 size_t run_hi = lo + 1;
6538 if (cmp(a[run_hi], a[lo])) // descending
6539 {
6540 while (run_hi < hi and cmp(a[run_hi], a[run_hi - 1]))
6541 ++run_hi;
6542 reverse_range(a, lo, run_hi);
6543 }
6544 else // ascending
6545 while (run_hi < hi and not cmp(a[run_hi], a[run_hi - 1]))
6546 ++run_hi;
6547 return run_hi - lo;
6548}
6549
6558template <typename T, class Compare>
6560 T *a, const size_t lo, const size_t hi, const size_t start,
6561 const Compare &cmp) noexcept(std::is_nothrow_move_constructible_v<T> and
6562 std::is_nothrow_move_assignable_v<T> and
6563 noexcept(static_cast<bool>(std::declval<const Compare &>()(
6564 std::declval<T &>(), std::declval<T &>()))))
6565
6566{
6567 size_t i = (start <= lo) ? lo + 1 : start;
6568 for (; i < hi; ++i)
6569 {
6570 T pivot = std::move(a[i]);
6571
6572 // Binary search for insertion point in [lo, i)
6573 size_t left = lo;
6574 size_t right = i;
6575 while (left < right)
6576 {
6577 const size_t mid = left + (right - left) / 2;
6578 if (cmp(pivot, a[mid]))
6579 right = mid;
6580 else
6581 left = mid + 1;
6582 }
6583
6584 // Shift elements [left, i) right by one
6585 for (size_t p = i; p > left; --p)
6586 a[p] = std::move(a[p - 1]);
6587 a[left] = std::move(pivot);
6588 }
6589}
6590
6608template <typename T, class Compare>
6610 const T &key, const T *a, const size_t len, const size_t hint,
6611 const Compare &cmp) noexcept(noexcept(static_cast<bool>(std::declval<const Compare &>()(
6612 std::declval<const T &>(), std::declval<const T &>()))))
6613{
6614 size_t last_ofs = 0;
6615 size_t ofs = 1;
6616
6617 if (cmp(a[hint], key)) // key > a[hint]: search right
6618 {
6619 const size_t max_ofs = len - hint;
6620 while (ofs < max_ofs and static_cast<bool>(cmp(a[hint + ofs], key)))
6621 {
6622 last_ofs = ofs;
6623 ofs = (ofs << 1) + 1;
6624 if (ofs > max_ofs)
6625 ofs = max_ofs;
6626 }
6627 last_ofs += hint;
6628 ofs += hint;
6629 }
6630 else // key <= a[hint]: search left
6631 {
6632 const size_t max_ofs = hint + 1;
6633 while (ofs < max_ofs and not static_cast<bool>(cmp(a[hint - ofs], key)))
6634 {
6635 last_ofs = ofs;
6636 ofs = (ofs << 1) + 1;
6637 if (ofs > max_ofs)
6638 ofs = max_ofs;
6639 }
6640 const size_t tmp = last_ofs;
6641 // Note: last_ofs may intentionally underflow if hint < ofs.
6642 // This is compensated by the subsequent ++last_ofs to effectively
6643 // start the binary search at index 0. This is safe for unsigned types.
6644 last_ofs = hint - ofs;
6645 ofs = hint - tmp;
6646 }
6647
6648 // Binary search in (last_ofs, ofs]
6649 ++last_ofs;
6650 while (last_ofs < ofs)
6651 {
6652 const size_t mid = last_ofs + (ofs - last_ofs) / 2;
6653 if (cmp(a[mid], key))
6654 last_ofs = mid + 1;
6655 else
6656 ofs = mid;
6657 }
6658 return ofs;
6659}
6660
6677template <typename T, class Compare>
6679 const T &key, const T *a, const size_t len, const size_t hint,
6680 const Compare &cmp) noexcept(noexcept(static_cast<bool>(std::declval<const Compare &>()(
6681 std::declval<const T &>(), std::declval<const T &>()))))
6682{
6683 size_t last_ofs = 0;
6684 size_t ofs = 1;
6685
6686 if (cmp(key, a[hint])) // key < a[hint]: search left
6687 {
6688 const size_t max_ofs = hint + 1;
6689 while (ofs < max_ofs and static_cast<bool>(cmp(key, a[hint - ofs])))
6690 {
6691 last_ofs = ofs;
6692 ofs = (ofs << 1) + 1;
6693 if (ofs > max_ofs)
6694 ofs = max_ofs;
6695 }
6696 const size_t tmp = last_ofs;
6697 // Note: last_ofs may intentionally underflow if hint < ofs.
6698 // This is compensated by the subsequent ++last_ofs to effectively
6699 // start the binary search at index 0. This is safe for unsigned types.
6700 last_ofs = hint - ofs;
6701 ofs = hint - tmp;
6702 }
6703 else // key >= a[hint]: search right
6704 {
6705 const size_t max_ofs = len - hint;
6706 while (ofs < max_ofs and not static_cast<bool>(cmp(key, a[hint + ofs])))
6707 {
6708 last_ofs = ofs;
6709 ofs = (ofs << 1) + 1;
6710 if (ofs > max_ofs)
6711 ofs = max_ofs;
6712 }
6713 last_ofs += hint;
6714 ofs += hint;
6715 }
6716
6717 ++last_ofs;
6718 while (last_ofs < ofs)
6719 {
6720 const size_t mid = last_ofs + (ofs - last_ofs) / 2;
6721 if (cmp(key, a[mid]))
6722 ofs = mid;
6723 else
6724 last_ofs = mid + 1;
6725 }
6726 return ofs;
6727}
6728
6735template <typename T, class Compare>
6736void merge_lo(T *a, const size_t base1, const size_t len1, const size_t base2, const size_t len2,
6737 T *tmp, const Compare &cmp)
6738{
6739 // Copy run1 into tmp
6740 for (size_t i = 0; i < len1; ++i)
6741 tmp[i] = std::move(a[base1 + i]);
6742
6743 size_t c1 = 0; // cursor into tmp (run1 copy)
6744 size_t c2 = base2; // cursor into a (run2)
6745 size_t dest = base1; // write cursor into a
6746 const size_t end1 = len1;
6747 const size_t end2 = base2 + len2;
6748
6749 while (c1 < end1 and c2 < end2)
6750 if (cmp(a[c2], tmp[c1]))
6751 a[dest++] = std::move(a[c2++]);
6752 else
6753 a[dest++] = std::move(tmp[c1++]);
6754
6755 // Copy remaining from tmp (run1)
6756 while (c1 < end1)
6757 a[dest++] = std::move(tmp[c1++]);
6758 // Remaining run2 elements are already in place
6759}
6760
6765template <typename T, class Compare>
6766void merge_hi(T *a, const size_t base1, const size_t len1, const size_t base2, const size_t len2,
6767 T *tmp, const Compare &cmp)
6768{
6769 // Copy run2 into tmp
6770 for (size_t i = 0; i < len2; ++i)
6771 tmp[i] = std::move(a[base2 + i]);
6772
6773 // Merge from the right (highest to lowest)
6774 size_t dest = base2 + len2; // one past end
6775 size_t c1 = base1 + len1; // one past end of run1 in a
6776 size_t c2 = len2; // one past end of run2 in tmp
6777
6778 while (c1 > base1 and c2 > 0)
6779 if (cmp(tmp[c2 - 1], a[c1 - 1]))
6780 a[--dest] = std::move(a[--c1]);
6781 else
6782 a[--dest] = std::move(tmp[--c2]);
6783
6784 // Copy remaining from tmp (run2)
6785 while (c2 > 0)
6786 a[--dest] = std::move(tmp[--c2]);
6787 // Remaining run1 elements are already in place
6788}
6789
6795template <typename T, class Compare>
6796void merge_at(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, const size_t at, T *tmp,
6797 const Compare &cmp)
6798{
6799 size_t base1 = run_base[at];
6800 size_t len1 = run_len[at];
6801 size_t base2 = run_base[at + 1];
6802 size_t len2 = run_len[at + 1];
6803
6804 // Record merged run
6805 run_len[at] = len1 + len2;
6806 if (at == stack_size - 3)
6807 {
6808 run_base[at + 1] = run_base[at + 2];
6809 run_len[at + 1] = run_len[at + 2];
6810 }
6811 --stack_size;
6812
6813 // Where does the first element of run2 go in run1?
6814 size_t k = gallop_right(a[base2], a + base1, len1, 0, cmp);
6815 base1 += k;
6816 len1 -= k;
6817 if (len1 == 0)
6818 return;
6819
6820 // Where does the last element of run1 go in run2?
6821 len2 = gallop_left(a[base1 + len1 - 1], a + base2, len2, len2 - 1, cmp);
6822 if (len2 == 0)
6823 return;
6824
6825 if (len1 <= len2)
6826 merge_lo(a, base1, len1, base2, len2, tmp, cmp);
6827 else
6828 merge_hi(a, base1, len1, base2, len2, tmp, cmp);
6829}
6830
6838template <typename T, class Compare>
6839void merge_collapse(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, T *tmp,
6840 const Compare &cmp)
6841{
6842 while (stack_size > 1)
6843 {
6844 long n = static_cast<long>(stack_size) - 2;
6845 if ((n > 0 and run_len[n - 1] <= run_len[n] + run_len[n + 1]) or
6846 (n > 1 and run_len[n - 2] <= run_len[n - 1] + run_len[n]))
6847 {
6848 if (run_len[n - 1] < run_len[n + 1])
6849 --n;
6850 merge_at(a, run_base, run_len, stack_size, n, tmp, cmp);
6851 }
6852 else if (run_len[n] <= run_len[n + 1])
6853 merge_at(a, run_base, run_len, stack_size, n, tmp, cmp);
6854 else
6855 break;
6856 }
6857}
6858
6860template <typename T, class Compare>
6861void merge_force_collapse(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, T *tmp,
6862 const Compare &cmp)
6863{
6864 while (stack_size > 1)
6865 {
6866 long n = static_cast<long>(stack_size) - 2;
6867 if (n > 0 and run_len[n - 1] < run_len[n + 1])
6868 --n;
6869 merge_at(a, run_base, run_len, stack_size, n, tmp, cmp);
6870 }
6871}
6872
6887template <typename T, class Compare>
6888void timsort_impl(T *a, const size_t n, const Compare &cmp)
6889{
6890 if (n < 2)
6891 return;
6892
6893 // For very small arrays, just use binary insertion sort
6894 if (n < 64)
6895 {
6896 const size_t run_len = count_run_and_make_ascending(a, 0, n, cmp);
6897 binary_insertion_sort(a, 0, n, run_len, cmp);
6898 return;
6899 }
6900
6901 const size_t minrun = compute_minrun(n);
6902
6903 // Run stack — log2(n) + 1 entries is sufficient
6904 // (timsort invariant guarantees Fibonacci-like growth)
6905 constexpr size_t MAX_STACK = 85; // enough for 2^64 elements
6906 size_t run_base_arr[MAX_STACK];
6907 size_t run_len_arr[MAX_STACK];
6908 size_t stack_size = 0;
6909
6910 // Temporary merge buffer — allocated once, sized to n/2
6911 // (merge_lo/merge_hi copy the smaller run)
6912 Array<T> tmp_buf = Array<T>::create(n / 2 + 1);
6913 T *tmp = &tmp_buf[0];
6914
6915 size_t lo = 0;
6916 size_t remaining = n;
6917
6918 while (remaining > 0)
6919 {
6920 // Find the next natural run
6921 size_t run_len = count_run_and_make_ascending(a, lo, lo + remaining, cmp);
6922
6923 // If the run is too short, extend it with insertion sort
6924 if (run_len < minrun)
6925 {
6926 const size_t force = remaining < minrun ? remaining : minrun;
6927 binary_insertion_sort(a, lo, lo + force, lo + run_len, cmp);
6928 run_len = force;
6929 }
6930
6931 // Push this run onto the stack
6932 ah_runtime_error_unless(stack_size < MAX_STACK)
6933 << "timsort: run stack overflow (stack_size=" << stack_size << " >= MAX_STACK=" << MAX_STACK
6934 << "); this should never happen";
6935 run_base_arr[stack_size] = lo;
6936 run_len_arr[stack_size] = run_len;
6937 ++stack_size;
6938
6939 // Maintain the stack invariants
6940 merge_collapse(a, run_base_arr, run_len_arr, stack_size, tmp, cmp);
6941
6942 lo += run_len;
6943 remaining -= run_len;
6944 }
6945
6946 // Force-merge all remaining runs
6947 merge_force_collapse(a, run_base_arr, run_len_arr, stack_size, tmp, cmp);
6948}
6949} // namespace timsort_detail
6950
6978template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
6979void timsort(T *a, const size_t n, const Compare &cmp = Compare())
6980{
6981 if (n == 0)
6982 return;
6983
6984 ah_invalid_argument_if(a == nullptr) << "timsort(): null pointer with non-zero length";
6985
6986 if (n < 2)
6987 return;
6988
6991}
6992
7005template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
7006void timsort(T *a, const long l, const long r, const Compare &cmp = Compare())
7007{
7008 ah_range_error_if(l < 0 or r < 0)
7009 << "timsort(): negative bounds [" << l << ", " << r << "] are not allowed";
7010
7011 if (l >= r)
7012 return;
7013
7014 ah_invalid_argument_if(a == nullptr)
7015 << "timsort(): null pointer contract violation for range [" << l << ", " << r
7016 << "]; cannot call timsort_detail::timsort_impl()";
7017
7019 timsort_detail::timsort_impl(a + l, static_cast<size_t>(r - l + 1), cmp);
7020}
7021
7031template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
7032void timsort(DynArray<T> &a, const Compare &cmp = Compare())
7033{
7034 bucket_sort_detail::apply_sort_with_temp<T>(
7035 a,
7036 bucket_sort_detail::sort_invoker_factory<static_cast<void (*)(T *, size_t, const Compare &)>(
7037 timsort)>{}(cmp),
7038 cmp);
7039}
7040
7050template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
7051void timsort(Array<T> &a, const Compare &cmp = Compare())
7052{
7053 if (a.size() < 2)
7054 return;
7055 timsort(&a[0], a.size(), cmp);
7056}
7057
7068template <typename T, size_t N, StrictWeakOrder<T> Compare = Aleph::less<T>>
7069 requires std::is_invocable_r_v<bool, Compare, const T &, const T &>
7070void timsort(T (&a)[N], const Compare &cmp = Compare())
7071{
7072 timsort(static_cast<T *>(a), N, cmp);
7073}
7074
7087template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
7088void timsort(DynList<T> &list, const Compare &cmp = Compare())
7089{
7090 bucket_sort_detail::apply_sort_with_temp<T>(
7091 list,
7092 bucket_sort_detail::sort_invoker_factory<static_cast<void (*)(T *, size_t, const Compare &)>(
7093 timsort)>{}(cmp),
7094 cmp);
7095}
7096
7109template <typename T, StrictWeakOrder<T> Compare = Aleph::less<T>>
7110void timsort(DynDlist<T> &list, const Compare &cmp = Compare())
7111{
7112 bucket_sort_detail::apply_sort_with_temp<T>(
7113 list,
7114 bucket_sort_detail::sort_invoker_factory<static_cast<void (*)(T *, size_t, const Compare &)>(
7115 timsort)>{}(cmp),
7116 cmp);
7117}
7118} // namespace Aleph
7119
7120#endif // TPL_SORT_UTILS_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_logic_error()
Throws std::logic_error unconditionally.
Definition ah-errors.H:490
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
#define ah_range_error_if(C)
Throws std::range_error if condition holds.
Definition ah-errors.H:356
#define ah_out_of_range_error()
Throws std::out_of_range unconditionally.
Definition ah-errors.H:759
STL-compatible iterator adapters for Aleph containers.
Functional programming utilities for Aleph-w containers.
General utility functions and helpers.
long double h
Definition btreepic.C:154
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
Definition tpl_array.H:194
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & base()
Return a reference to the first element of array.
Definition tpl_array.H:408
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
void putn(const size_t n)
Reserve n additional logical slots in the array without value-initializing them.
Definition tpl_array.H:392
Helper class to compare nodes of a linked list.
bool operator()(Tlink *l1, Tlink *l2) const noexcept(noexcept(static_cast< bool >(std::declval< const Compare & >()(std::declval< Tnode< T > * >() ->get_data(), std::declval< Tnode< T > * >() ->get_data()))))
Compares two nodes based on their data.
Compare_Tnode(Compare cmp_fct=Compare()) noexcept(std::is_nothrow_copy_constructible_v< Compare >)
Construct from a comparison functor.
Read-only view of an Aleph iterator: the iterator of a constant container.
auto has_curr() const noexcept(noexcept(std::declval< I & >().has_curr())) -> decltype(std::declval< I & >().has_curr())
true if there is a current item.
auto get_curr() const noexcept(noexcept(std::declval< I & >().get_curr())) -> const_iterator_detail::const_item_t< decltype(std::declval< I & >().get_curr())>
The current item, read-only.
auto next_ne() noexcept(noexcept(std::declval< I & >().next_ne())) -> decltype(std::declval< I & >().next_ne())
next() without checks.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Dnode< T > * remove_first_ne() noexcept
Remove the first node and return its address.
Definition tpl_dnode.H:152
T & get_data() noexcept
Return a modifiable reference to the data contained in the node.
Definition tpl_dnode.H:266
size_t size() const noexcept
Return the current dimension of array.
bool exist(const size_t i) const
Return true if the i-th entry is accessible.
Iterator dynamic list.
void next_ne() noexcept
Move the iterator one position forward guaranteeing no exception.
T & get_curr_ne() const noexcept
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
Iterator on the items of list.
Definition htlist.H:1614
T & get_curr_ne() const noexcept
Return the current link guaranteeing no exception. Be careful.
Definition htlist.H:1669
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T & get_first_ne() noexcept
Return the first item of the list without exception.
Definition htlist.H:1512
T & insert(const T &item)
Definition htlist.H:1308
T remove_first_ne() noexcept(std::is_nothrow_move_constructible_v< T >)
See remove_ne().
Definition htlist.H:1467
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Fixed length stack.
size_t size() const noexcept
Return the number of elements stored in the stack.
bool is_empty() const noexcept
Return true if stack is empty.
T pop() noexcept
Pop by moving the top of stack.
T & push(const T &data) noexcept(std::is_nothrow_copy_assignable_v< T >)
Push a copy of data
void next_ne() noexcept
Move the iterator one position forward guaranteeing no exception.
Definition htlist.H:1012
Slinknc * get_curr() const
Definition htlist.H:997
bool has_curr() const noexcept
Definition htlist.H:969
Single linked list of nodes.
Definition htlist.H:420
Slinknc * get_first() const noexcept
Definition htlist.H:463
constexpr bool is_empty() const noexcept
Definition htlist.H:434
void concat_list(HTList &l) noexcept
See concat(HTList & l).
Definition htlist.H:566
void append(Slinknc *link) noexcept
Definition htlist.H:518
Slinknc * remove_first_ne() noexcept
Remove the header item from the list.
Definition htlist.H:667
void insert(Slinknc *link) noexcept
Definition htlist.H:499
Slinknc * get_last() const noexcept
Return the last item of the list (nullptr if the list is empty)
Definition htlist.H:475
bool is_unitarian_or_empty() const noexcept
Return true if list contains one element or is empty.
Definition htlist.H:448
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Comparator wrapper that inverts the comparison order.
bool operator()(const T &e1, const T &e2) const noexcept(noexcept(static_cast< bool >(std::declval< const Compare & >()(e2, e1))))
Compare in reverse order: returns cmp(e2, e1).
Negate_Compare(Compare __cmp=Compare()) noexcept(std::is_nothrow_copy_assignable_v< Compare >)
Construct from a comparator.
Link of a single linked list non-circular and without header node.
Definition htlist.H:95
void insert(Slinknc *p) noexcept
insert(p) inserts the node pointed by p after this.
Definition htlist.H:146
Value concept accepted by counting sort overloads.
Integral value accepted by linear-time integer sorting algorithms.
Value concept accepted by radix sort overloads.
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
Singly linked list implementations with head-tail access.
const long double offset[]
Offset values indexed by symbol string length (bounded by MAX_OFFSET_INDEX)
void insertion_sort_range(T *a, const size_t lo, const size_t hi, const Compare &cmp) noexcept(std::is_nothrow_move_constructible_v< T > and std::is_nothrow_move_assignable_v< T > and noexcept(static_cast< bool >(std::declval< const Compare & >()(std::declval< T & >(), std::declval< T & >()))))
Insertion sort a sub-array [lo, hi).
void apply_sort_with_temp(Container &a, SortFn sort_fn, const Compare &cmp)
Helper to sort any container by copying to a temporary array.
void bucket_sort_impl(T *a, const size_t n, const size_t num_buckets, const BucketKey &bucket_key, const Compare &cmp)
Core bucket sort implementation on a raw pointer range.
void insertion_sort_range(T *begin, T *end, const Compare &cmp)
Sort [begin, end) by insertion.
Partitioned< T > partition_by_blocks(T *begin, T *end, const Compare &cmp)
Partition [begin, end) around the pivot *begin by blocks: the items less than the pivot go before it,...
void sort_loop(T *begin, T *end, const Compare &cmp, int bad_allowed, bool leftmost, bool by_blocks)
Sort [begin, end): the loop of introsort().
T * partition_left(T *begin, T *end, const Compare &cmp)
Partition [begin, end) around the pivot *begin when it equals the item before begin,...
constexpr long Ninther_Threshold
Ranges longer than this one take their pivot from nine items.
constexpr long Few_Swaps_Ratio
A partition that swaps fewer than one item in this many of its range leaves its subranges to the part...
std::conditional_t< std::is_trivially_copyable_v< T >, const T, const T & > Pivot_Ref
The pivot as a partition reads it: a copy of a trivially copyable item, which the compiler can keep i...
void sort2(T *a, T *b, const Compare &cmp)
Swap *a and *b if *b is less than *a.
bool partial_insertion_sort_range(T *begin, T *end, const Compare &cmp)
Sort [begin, end) by insertion, unless that takes more than Partial_Insertion_Limit moves.
void swap_offsets(T *first, T *last, const unsigned char *offsets_l, const unsigned char *offsets_r, const long num, const bool use_swaps)
Move the num pairs of items on the wrong sides, at first + offsets_l[i] and at last - offsets_r[i].
constexpr long Block_Size
Items that a partition by blocks compares at a time.
constexpr long Insertion_Threshold
Ranges shorter than this one are sorted by insertion.
void sort3(T *a, T *b, T *c, const Compare &cmp)
Sort *a, *b and *c.
constexpr long Partial_Insertion_Limit
Moves after which the insertion sort of a range that a partition found in order gives up.
T * insert_back(T *begin, T *cur, const Compare &cmp)
Move *cur, which is less than *(cur - 1), back into the sorted range [begin, cur),...
Partitioned< T > partition_by_branches(T *begin, T *end, const Compare &cmp)
Partition [begin, end) around the pivot *begin with branches, as partition_by_blocks() does by blocks...
void radix_sort_impl(C< IntT > &a)
Internal radix-sort implementation for array-like containers.
void median_of_three_to_last(C< T > &a, const long l, const long r, const Compare &cmp)
Put in order a(l), a(m) and a(r), with m the middle of [l, r], and move their median to a(r),...
constexpr radix_unsigned_t< IntT > radix_key(const IntT value) noexcept
Map an integer value to an unsigned radix key.
IntT counting_value_from_bucket(const size_t bucket, const IntT min_key) noexcept
Retrieve the original value from a bucket index in counting sort.
std::make_unsigned_t< std::remove_cv_t< IntT > > counting_unsigned_t
Unsigned counterpart used to measure counting-sort key ranges.
constexpr long Median_Of_Three_Min_Size
Ranges with fewer items than this one keep their last item as the pivot of partition(): there the med...
std::make_unsigned_t< std::remove_cv_t< IntT > > radix_unsigned_t
Unsigned key type used by radix sort passes.
size_t counting_bucket(const IntT value, const IntT min_key) noexcept
Map a value to its bucket index in counting sort.
size_t counting_bucket_count(const IntT min_key, const IntT max_key)
Compute the number of buckets required for a counting sort range.
void counting_sort_impl(C< IntT > &a)
Internal implementation of counting sort for containers.
void merge_force_collapse(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, T *tmp, const Compare &cmp)
Force-merge all remaining runs at the end.
void merge_at(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, const size_t at, T *tmp, const Compare &cmp)
Merge runs[at] with runs[at+1].
void binary_insertion_sort(T *a, const size_t lo, const size_t hi, const size_t start, const Compare &cmp) noexcept(std::is_nothrow_move_constructible_v< T > and std::is_nothrow_move_assignable_v< T > and noexcept(static_cast< bool >(std::declval< const Compare & >()(std::declval< T & >(), std::declval< T & >()))))
Binary insertion sort on [lo, hi) starting from start.
size_t gallop_left(const T &key, const T *a, const size_t len, const size_t hint, const Compare &cmp) noexcept(noexcept(static_cast< bool >(std::declval< const Compare & >()(std::declval< const T & >(), std::declval< const T & >()))))
Gallop left: find the insertion point for a key in a sorted range.
void timsort_impl(T *a, const size_t n, const Compare &cmp)
Core Timsort implementation.
size_t count_run_and_make_ascending(T *a, const size_t lo, const size_t hi, const Compare &cmp)
Find the length of the natural run starting at lo.
void merge_hi(T *a, const size_t base1, const size_t len1, const size_t base2, const size_t len2, T *tmp, const Compare &cmp)
Merge two adjacent sorted runs where len1 >= len2.
void merge_collapse(T *a, size_t *run_base, size_t *run_len, size_t &stack_size, T *tmp, const Compare &cmp)
Maintain the timsort run stack invariants.
void merge_lo(T *a, const size_t base1, const size_t len1, const size_t base2, const size_t len2, T *tmp, const Compare &cmp)
Merge two adjacent sorted runs a[base1..base1+len1) and a[base2..base2+len2) using temporary buffer.
constexpr size_t compute_minrun(size_t n) noexcept
Compute the minimum run length for timsort.
void reverse_range(T *a, size_t lo, size_t hi) noexcept(std::is_nothrow_swappable_v< T >)
Reverse elements in [lo, hi).
size_t gallop_right(const T &key, const T *a, const size_t len, const size_t hint, const Compare &cmp) noexcept(noexcept(static_cast< bool >(std::declval< const Compare & >()(std::declval< const T & >(), std::declval< const T & >()))))
Gallop right: find the insertion point for a key in a sorted range.
Main namespace for Aleph-w library functions.
Array< const T * > build_index_ptr(const C< T > &a, const Compare &cmp=Compare())
Build an index array of pointers for indirect sorting (const version).
DynList< size_t > binary_search_dup(const C< T > &a, const T &x, const Compare &cmp=Compare())
Binary search for all occurrences of a value.
and std::convertible_to< std::invoke_result_t< const KeyFn &, size_t >, int > void counting_sort_indices(Array< size_t > &sa, Array< size_t > &tmp, const size_t n, const int min_key, const int max_key, const KeyFn &key_of)
Stable counting sort on an index array by integer keys.
void insertion_sort(T *a, const long l, const long r, const Compare &cmp=Compare()) noexcept(noexcept(static_cast< bool >(cmp(std::declval< T & >(), std::declval< T & >()))) and std::is_nothrow_move_constructible_v< T > and std::is_nothrow_move_assignable_v< T >)
Sort an array using insertion sort.
long search_min(T *a, const long l, const long r, const Compare &cmp=Compare())
Returns the smallest element of the array a between l and r.
bool is_sorted(const Container< T > &cont, const Compare &cmp=Compare())
Check if a container is sorted in ascending order.
static std::pair< long, long > partition_three_way(T *a, long l, long r, const Compare &cmp)
Array< const T * > stable_build_index_ptr(const C< T > &a, const Compare &cmp=Compare())
Build a stable index array of pointers for indirect sorting (const version).
static void insertion_sort_range(Container &a, long l, long r, const Compare &cmp)
long select_pivot_op_impl(const Container &a, const long l, const long r, const Compare &cmp)
Implementation of pivot selection using operator().
std::pair< bool, size_t > search_inversion(const Container< T > &cont, const Compare &cmp=Compare())
Find the first inversion in a container.
void heapsort_subrange(DynArray< T > &a, const long l, const long r, const Compare &cmp)
Heapsort implementation for a subrange of a DynArray.
size_t introsort_depth_limit(size_t n) noexcept
Forward declaration.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
long select_pivot_op(const DynArray< T > &a, const long l, const long r, const Compare &cmp=Compare())
Selects a pivot element as the median between the ends and the center.
Dnode< T > * dlink_random_search(Dlink &list, const T &x, const Compare &cmp=Compare())
Random search for an element in a dlink list.
Array< size_t > stable_build_index(const C &a, const Compare &cmp=Compare())
Build a stable index array for indirect sorting.
void sift_down(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position l downwards.
void sift_down_subrange(DynArray< T > &a, long start, const long n, const long offset, const Compare &cmp)
Sift down operation for heapsort on a DynArray subrange.
void quicksort_no_tail(T *a, long l, long r, const Compare &cmp=Compare())
Quicksort implementation with tail-recursion optimization.
long random_search(T *a, const T &x, const long l, const long r, const Compare &cmp=Compare())
Random search for an element in an array.
size_t Quicksort_Threshold
Threshold for using quicksort vs simpler algorithms.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
const int Not_Found
Return value for search functions when element is not found.
void counting_sort(DynArray< T > &a)
Stable counting sort for integral DynArray values.
std::pair< TgtContainer< typename SrcContainer::Item_Type >, TgtContainer< typename SrcContainer::Item_Type > > partition(const SrcContainer &c, std::function< bool(const typename SrcContainer::Item_Type &)> operation)
Partition a container into two based on a predicate.
std::pair< bool, size_t > test_sorted(const Container< T > &cont, const Compare &cmp=Compare())
Test if a container is sorted, returning the inversion position.
void introsort_loop(T *a, long l, long r, size_t depth_limit, const Compare &cmp)
Quicksort loop with a depth limit, after which heapsort sorts the range: the loop of introsort() befo...
long search_max(T *a, const long l, const long r, const Compare &cmp=Compare())
Returns the maximum element of the array a between l and r.
void timsort(T *a, const size_t n, const Compare &cmp=Compare())
Timsort — adaptive, stable, natural merge sort.
void mergeinsertsort(Tlist< T > &list, const Compare &cmp=Compare(), const size_t lsz=Aleph::Insertion_Threshold)
Sort a list by mergesort combined with the insert method.
void insert_sorted(Dlink &list, Dlink *p, const Compare &cmp)
Inserts a node orderly into a doubly linked list.
Dlink * dlink_random_select(Dlink &list, const size_t i, const Compare &cmp=Compare())
Random selection of the ith element from a list based on Dlink.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
T * bsearch(C< T > &a, const T &x, const Compare &cmp=Compare())
Search for a value in a sorted container returning a pointer.
Array< size_t > build_index(const C &a, const Compare &cmp=Compare())
Build an index array for indirect sorting.
void list_insertion_sort(ListType &list, const Compare &cmp)
Generic insertion sort for linked lists.
const T & random_select(DynArray< T > &a, const long i, const Compare &cmp=Compare())
Select the i-th smallest element in a DynArray.
void bucket_sort(T *a, const size_t n, const size_t num_buckets, const BucketKey &bucket_key, const Compare &cmp=Compare())
Bucket sort with user-supplied bucket mapping.
and
Check uniqueness with explicit hash + equality functors.
static long back_index(const long i) noexcept
Convert a 1-based heap index to a 0-based array index.
void bubble_sort(DynArray< T > &a, const Compare &cmp=Compare())
Sort a dynamic array using bubble sort.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
void quicksort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using iterative quicksort with optimizations.
void radix_sort(DynArray< T > &a)
LSD radix sort for integral DynArray values.
void mergesort(T *a, const long l, const long r, Array< T > &buf, Compare cmp)
Sort an array using merge sort with a reusable buffer.
void shellsort(DynArray< T > &a, const Compare &cmp=Compare())
Sort a dynamic array using Shell sort.
void selection_sort(T *a, const size_t n, const Compare &cmp=Compare()) noexcept(noexcept(static_cast< bool >(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v< T >)
Sort an array using the selection sort algorithm.
bool are_equals(const T &op1, const T &op2, Compare &&cmp=Compare())
Determines if operands are equal using a comparison operator.
void __link_mergeinsertsort(Tlist &list, const size_t n, const Compare &cmp, const size_t lsz)
static std::pair< long, long > partition_three_way_op(Container &a, long l, long r, const Compare &cmp)
constexpr void faster_heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Optimized version of heapsort.
Itor3 merge(Itor1 source1Beg, Itor1 source1End, Itor2 source2Beg, Itor2 source2End, Itor3 destBeg)
Merge two sorted ranges.
Definition ahAlgo.H:1410
void quicksort_rec_min(T *a, const long l, const long r, const Compare &cmp=Compare())
Sorts an array according to the quicksort method with minimum space consumption.
long sequential_search(T *a, const T &x, const long l, const long r, Equal eq=Equal())
Linear search for an element in an array.
Link * search_extreme(const Link &list, const Compare &cmp)
Find the extreme (minimum or maximum) element in a linked list.
bool binary_search(Itor beg, Itor end, const T &value)
Binary search for a value.
Definition ahAlgo.H:1284
static const T & __random_select(T *a, const long i, long l, long r, const Compare &cmp)
void quicksort_rec(T *a, const long l, const long r, const Compare &cmp=Compare())
Recursively sort an array using quicksort.
DynList< long > binindex_dup(const C< T > &a, const T &x, const Compare &cmp=Compare())
Returns the indices of all occurrences of a value in a sorted container.
bool is_inversely_sorted(const Container< T > &cont, const Compare &cmp=Compare())
Check if a container is sorted in descending order.
DynList< const T * > bsearch_dup(const C< T > &a, const T &x, const Compare &cmp=Compare())
Search for all occurrences of a value returning pointers (const version).
long partition_op_impl(Container &a, const long l, const long r, const Compare &cmp)
Implementation of partitioning using operator().
constexpr void heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Sort an array using the heapsort algorithm.
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
long select_pivot(T *a, long l, long r, const Compare &cmp=Compare()) noexcept(noexcept(static_cast< bool >(cmp(a[0], a[0]))) and std::is_nothrow_swappable_v< T >)
Select a pivot for partitioning using median-of-three.
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
long binindex(const C< T > &a, const T &x, const Compare &cmp=Compare())
Returns the index where a value appears (or should be inserted) in a sorted container.
void quicksort_insertion(T *a, const long l, const long r, const Compare &cmp=Compare())
Sorts an array by the improved quicksort method.
size_t Insertion_Threshold
Threshold for switching to insertion sort in hybrid algorithms.
long binary_search_rec(T *a, const T &x, const long l, const long r, const Compare &cmp=Compare())
Recursive binary search on an ordered array.
long partition_op(DynArray< T > &a, const long l, const long r, const Compare &cmp=Compare())
Partition a DynArray using operator().
T & sift_up(T *ptr, const size_t l, const size_t r, Compare &cmp)
Restore the heap property by moving the element at position r upwards.
void merge_lists(Tlist &l1, Tlist &l2, Tlist &result, const Compare &cmp=Compare())
Merge two sorted lists into a single sorted list.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
void push2(Stack &stack, const A &a, const B &b)
Push two values onto a stack.
void quicksort_op(C< T > &a, const Compare &cmp=Compare(), const size_t threshold=Quicksort_Threshold)
Optimized quicksort for containers using operator().
STL namespace.
Comparator specialization for Dnode objects.
Compare_Dnode(const Compare &cmp=Compare()) noexcept(std::is_nothrow_copy_constructible_v< Compare >)
Factory for bucket_sort with extra parameters.
Factory for lambdas that forward to a sort function.
What a partition did: the place of the pivot, whether the range was already partitioned,...
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< int > l1
DynList< int > l2
static int * k
Gsl_Compatible_Rng r
Fixed-capacity binary heap and heapsort algorithms.
Stack implementations backed by dynamic or fixed arrays.
Dynamic array container with automatic resizing.
Lazy and scalable dynamic array implementation.
Dynamic doubly linked list implementation.
DynList< int > l