Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
sort_utils.cc
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
31
37#include <gtest/gtest.h>
38
39#include <algorithm>
40#include <chrono>
41#include <cmath>
42#include <cstdint>
43#include <cstdlib>
44#include <functional>
45#include <limits>
46#include <memory>
47#include <random>
48#include <stdexcept>
49#include <string>
50#include <type_traits>
51#include <vector>
52#include <array>
53
54#include <tpl_sort_utils.H>
55#include <tpl_dynArray.H>
56#include <tpl_array.H>
57#include <tpl_dynList.H>
58#include <tpl_dynDlist.H>
59#include <tpl_dnode.H>
60
61using namespace Aleph;
62using namespace std;
63
64namespace {
65
66static_assert(CountingSortable<int>);
67static_assert(CountingSortable<unsigned long long>);
68static_assert(not CountingSortable<bool>);
69static_assert(RadixSortable<int>);
70static_assert(RadixSortable<unsigned long long>);
71static_assert(not RadixSortable<bool>);
72
79static DynArray<int> make_dynarray(std::initializer_list<int> xs)
80{
82 a.reserve(xs.size());
83 size_t i = 0;
84 for (const int x : xs)
85 a(i++) = x;
86 return a;
87}
88
89template <class Compare>
90std::vector<size_t> stable_index_reference(const std::vector<int> &values,
91 const Compare &cmp)
92{
93 std::vector<size_t> ref(values.size());
94 for (size_t i = 0; i < ref.size(); ++i)
95 ref[i] = i;
96
97 std::stable_sort(ref.begin(), ref.end(),
98 [&values, &cmp](const size_t i, const size_t j)
99 {
100 return cmp(values[i], values[j]);
101 });
102
103 return ref;
104}
105
106template <class Index>
107void expect_index_matches_reference(const Index &idx,
108 const std::vector<size_t> &ref)
109{
110 ASSERT_EQ(idx.size(), ref.size());
111 for (size_t i = 0; i < ref.size(); ++i)
112 EXPECT_EQ(idx(i), ref[i]) << "position " << i;
113}
114
115template <class Compare>
116void expect_stable_build_index_matches_reference_exhaustively(const Compare &cmp)
117{
118 constexpr size_t max_n = 7;
119 constexpr size_t alphabet = 3;
120
121 for (size_t n = 0; n <= max_n; ++n)
122 {
123 size_t cases = 1;
124 for (size_t i = 0; i < n; ++i)
125 cases *= alphabet;
126
127 for (size_t code = 0; code < cases; ++code)
128 {
129 std::vector<int> values(n);
130 size_t x = code;
131 for (size_t i = 0; i < n; ++i)
132 {
133 values[i] = static_cast<int>(x % alphabet);
134 x /= alphabet;
135 }
136
137 const auto idx = stable_build_index(values, cmp);
138 const auto ref = stable_index_reference(values, cmp);
139 expect_index_matches_reference(idx, ref);
140 }
141 }
142}
143
144static DynList<int> make_dynlist(std::initializer_list<int> xs)
145{
147 for (int x : xs)
148 l.append(x);
149 return l;
150}
151
152static DynDlist<int> make_dyndlist(std::initializer_list<int> xs)
153{
155 for (int x : xs)
156 l.append(x);
157 return l;
158}
159
160static Dnode<int> make_dnode_list(std::initializer_list<int> xs)
161{
163 for (int x : xs)
164 h.append(new Dnode<int>(x));
165 return h;
166}
167
175static void delete_all_nodes(Dnode<int> & h)
176{
177 while (not h.is_empty())
178 delete h.remove_first_ne();
179}
180
187template <typename T>
188static void sort_dynarray(DynArray<T> & a)
189{
190 quicksort(a);
191}
192
204template <typename T>
205static void expect_same_dynarray(const DynArray<T> & a, const DynArray<T> & b)
206{
207 EXPECT_EQ(a.size(), b.size());
208 if (a.size() != b.size())
209 return;
210 for (size_t i = 0; i < a.size(); ++i)
211 EXPECT_EQ(a(i), b(i));
212}
213
221template <typename T>
222static DynArray<uintptr_t> dynlist_node_addresses(const DynList<T> & l)
223{
225 ret.reserve(l.size());
226 size_t i = 0;
227 for (HTList::Iterator it(l); it.has_curr(); it.next())
228 ret(i++) = reinterpret_cast<uintptr_t>(it.get_curr());
229 sort_dynarray(ret);
230 return ret;
231}
232
243template <typename T>
244static DynArray<uintptr_t> dyndlist_node_addresses(const DynDlist<T> & l)
245{
247 ret.reserve(l.size());
248 size_t i = 0;
249 for (typename Dnode<T>::Iterator it(l); it.has_curr(); it.next())
250 ret(i++) = reinterpret_cast<uintptr_t>(it.get_curr());
251 sort_dynarray(ret);
252 return ret;
253}
254
255TEST(SortUtilsSortedness, allows_equal)
256{
257 DynList<int> l = make_dynlist({1, 1, 2, 2, 3});
258 EXPECT_TRUE(is_sorted(l));
259 EXPECT_TRUE(test_sorted(l).first);
260 EXPECT_TRUE(search_inversion(l).first);
261}
262
263TEST(SortUtilsSortedness, detects_inversion)
264{
265 DynList<int> l = make_dynlist({1, 3, 2, 4});
266 EXPECT_FALSE(is_sorted(l));
267 auto inv = search_inversion(l);
268 EXPECT_FALSE(inv.first);
269 EXPECT_EQ(inv.second, 2u);
270}
271
272TEST(SortUtilsSortedness, inversely_sorted)
273{
274 DynList<int> l = make_dynlist({5, 4, 4, 2, 1});
275 EXPECT_TRUE(is_inversely_sorted(l));
276 EXPECT_FALSE(is_sorted(l));
277}
278
279TEST(SortUtilsArraySorts, selection_sort_empty_and_single)
280{
281 int a0[1] = {0};
282 selection_sort(a0, 0);
283 selection_sort(a0, 1);
284 EXPECT_EQ(a0[0], 0);
285}
286
287TEST(SortUtilsArraySorts, selection_sort_basic)
288{
289 int a[] = {3, 1, 2, 1, 0};
290 selection_sort(a, sizeof(a) / sizeof(a[0]));
291 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
292}
293
294TEST(SortUtilsArraySorts, insertion_sort_subrange)
295{
296 auto a = make_dynarray({10, 9, 3, 2, 1, 8, 7});
297 // sort only [2..4] (3,2,1)
298 insertion_sort(a, 2, 4);
299 EXPECT_EQ(a(0), 10);
300 EXPECT_EQ(a(1), 9);
301 EXPECT_EQ(a(2), 1);
302 EXPECT_EQ(a(3), 2);
303 EXPECT_EQ(a(4), 3);
304 EXPECT_EQ(a(5), 8);
305 EXPECT_EQ(a(6), 7);
306}
307
308TEST(SortUtilsArraySorts, selection_sort_dynarray)
309{
310 auto a = make_dynarray({3, 1, 2, 1, 0});
312 for (size_t i = 1; i < a.size(); ++i)
313 ASSERT_LE(a(i - 1), a(i));
314}
315
316TEST(SortUtilsArraySorts, selection_sort_dynarray_custom_compare_desc)
317{
318 auto a = make_dynarray({3, 1, 2, 1, 0});
320 for (size_t i = 1; i < a.size(); ++i)
321 ASSERT_GE(a(i - 1), a(i));
322}
323
324TEST(SortUtilsArraySorts, bubble_sort_dynarray)
325{
326 auto a = make_dynarray({3, 1, 2, 1, 0});
327 bubble_sort(a);
328 for (size_t i = 1; i < a.size(); ++i)
329 ASSERT_LE(a(i - 1), a(i));
330}
331
332TEST(SortUtilsArraySorts, bubble_sort_dynarray_already_sorted_with_duplicates)
333{
334 auto a = make_dynarray({0, 0, 1, 1, 2, 2});
335 bubble_sort(a);
336 for (size_t i = 1; i < a.size(); ++i)
337 ASSERT_LE(a(i - 1), a(i));
338 EXPECT_EQ(a(0), 0);
339 EXPECT_EQ(a(5), 2);
340}
341
342static bool is_min_heap(const DynArray<int> & a, size_t n)
343{
344 if (n <= 1)
345 return true;
346
347 for (size_t child = 2; child <= n; ++child)
348 {
349 size_t parent = child / 2;
350 if (a(parent - 1) > a(child - 1))
351 return false;
352 }
353 return true;
354}
355
356TEST(SortUtilsHelpers, select_pivot_op_dynarray_median_of_three)
357{
358 auto a = make_dynarray({5, 99, 0, 99, 99, 3, 99});
359 // l=0 => 5, m=3 => 99, r=6 => 99 => median is 99 => either m or r
360 long p = select_pivot_op<int>(a, 0, 6);
361 EXPECT_TRUE(p == 3 || p == 6);
362
363 auto b = make_dynarray({10, 99, 5, 99, 99, 99, 0});
364 // l=0 => 10, m=3 => 99, r=6 => 0 => median is 10 => l
365 EXPECT_EQ(select_pivot_op<int>(b, 0, 6), 0);
366
367 auto c = make_dynarray({0, 99, 99, 5, 99, 99, 10});
368 // l=0 => 0, m=3 => 5, r=6 => 10 => median is 5 => m
369 EXPECT_EQ(select_pivot_op<int>(c, 0, 6), 3);
370}
371
372TEST(SortUtilsHelpers, select_pivot_op_array_small_range_returns_r)
373{
374 Array<int> a;
375 for (int x : {5, 4, 3, 2, 1, 0})
376 a.append(x);
377
378 // r - l <= 5 => returns r
379 EXPECT_EQ(select_pivot_op<int>(a, 0, 5), 5);
380}
381
382TEST(SortUtilsHelpers, partition_op_dynarray_invariants)
383{
384 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
385 std::vector<int> before;
386 before.reserve(a.size());
387 for (size_t i = 0; i < a.size(); ++i)
388 before.push_back(a(i));
389
390 long p = partition_op<int>(a, 0, static_cast<long>(a.size() - 1));
391 ASSERT_GE(p, 0);
392 ASSERT_LT(static_cast<size_t>(p), a.size());
393
394 const int pivot = a(p);
395 for (long i = 0; i < p; ++i)
396 ASSERT_FALSE(Aleph::less<int>()(pivot, a(i)));
397 for (long i = p + 1; i < static_cast<long>(a.size()); ++i)
398 ASSERT_FALSE(Aleph::less<int>()(a(i), pivot));
399
400 std::vector<int> after;
401 after.reserve(a.size());
402 for (size_t i = 0; i < a.size(); ++i)
403 after.push_back(a(i));
404 std::sort(before.begin(), before.end());
405 std::sort(after.begin(), after.end());
406 EXPECT_EQ(before, after);
407}
408
409TEST(SortUtilsHelpers, partition_op_array_invariants)
410{
411 Array<int> a;
412 for (int x : {4, 1, 3, 2, 0, 2})
413 a.append(x);
414
415 std::vector<int> before;
416 before.reserve(a.size());
417 for (size_t i = 0; i < a.size(); ++i)
418 before.push_back(a(i));
419
420 long p = partition_op<int>(a, 0, static_cast<long>(a.size() - 1));
421 ASSERT_GE(p, 0);
422 ASSERT_LT(static_cast<size_t>(p), a.size());
423
424 const int pivot = a(p);
425 for (long i = 0; i < p; ++i)
426 ASSERT_FALSE(Aleph::less<int>()(pivot, a(i)));
427 for (long i = p + 1; i < static_cast<long>(a.size()); ++i)
428 ASSERT_FALSE(Aleph::less<int>()(a(i), pivot));
429
430 std::vector<int> after;
431 after.reserve(a.size());
432 for (size_t i = 0; i < a.size(); ++i)
433 after.push_back(a(i));
434 std::sort(before.begin(), before.end());
435 std::sort(after.begin(), after.end());
436 EXPECT_EQ(before, after);
437}
438
439TEST(SortUtilsHelpers, __random_select_dynarray_and_array)
440{
441 {
442 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
443 auto expected = std::vector<int>{4, 1, 3, 2, 0, 2};
444 std::sort(expected.begin(), expected.end());
445 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 0, 0, 5)), expected[0]);
446 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 3, 0, 5)), expected[3]);
447 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 5, 0, 5)), expected[5]);
448 }
449
450 {
451 Array<int> a;
452 for (int x : {4, 1, 3, 2, 0, 2})
453 a.append(x);
454 auto expected = std::vector<int>{4, 1, 3, 2, 0, 2};
455 std::sort(expected.begin(), expected.end());
456 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 0, 0, 5)), expected[0]);
457 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 3, 0, 5)), expected[3]);
458 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 5, 0, 5)), expected[5]);
459 }
460}
461
462TEST(SortUtilsHelpers, back_index_and_negate_compare)
463{
464 EXPECT_EQ(back_index(10), 9);
465
467 EXPECT_TRUE(nc(2, 1));
468 EXPECT_FALSE(nc(1, 2));
469}
470
471TEST(SortUtilsHelpers, select_pivot_and_partition_raw)
472{
473 int a[] = {4, 1, 3, 2, 0, 2};
475 int p = select_pivot<int, Aleph::less<int>>(a, 0, 5, cmp);
476 EXPECT_GE(p, 0);
477 EXPECT_LE(p, 5);
478
479 int q = partition<int, Aleph::less<int>>(a, 0, 5, cmp);
480 EXPECT_GE(q, 0);
481 EXPECT_LE(q, 5);
482}
483
484TEST(SortUtilsHelpers, merge_raw_partitions)
485{
486 // [0..2] and [3..5] are already sorted
487 int a[] = {0, 2, 4, 1, 3, 5};
488 merge(a, 0, 2, 5, Aleph::less<int>());
489 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
490}
491
492TEST(SortUtilsHelpers, push2_fixedstack)
493{
494 FixedStack<int> st(10);
495 push2(st, 1, 2);
496 EXPECT_EQ(st.pop(), 1);
497 EXPECT_EQ(st.pop(), 2);
498 EXPECT_TRUE(st.is_empty());
499}
500
501TEST(SortUtilsHelpers, quicksort_no_tail_pointer)
502{
503 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
504 quicksort_no_tail(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
505 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
506}
507
508TEST(SortUtilsHelpers, compare_tnode_direct)
509{
510 Snodenc<int> n1(1), n2(2);
512 EXPECT_TRUE(cmp(static_cast<Slinknc *>(&n1), static_cast<Slinknc *>(&n2)));
513 EXPECT_TRUE(cmp(static_cast<Slinknc *>(&n1), 5));
514}
515
516TEST(SortUtilsHelpers, insert_sorted_dlink_and_list_insertion_sort)
517{
519 Dlink & base = static_cast<Dlink &>(h);
520
521 auto * n2 = new Dnode<int>(2);
522 auto * n0 = new Dnode<int>(0);
523 auto * n1 = new Dnode<int>(1);
524
527
528 insert_sorted<Cmp>(base, n2, cmp);
529 insert_sorted<Cmp>(base, n0, cmp);
530 insert_sorted<Cmp>(base, n1, cmp);
531 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
532
533 // list_insertion_sort on Dlink
534 Dnode<int> h2 = make_dnode_list({3, 1, 2, 0});
535 Dlink & base2 = static_cast<Dlink &>(h2);
536 list_insertion_sort<Dlink, Cmp>(base2, cmp);
537 EXPECT_EQ(search_extreme<int>(h2, Aleph::less<int>())->get_data(), 0);
538
539 delete_all_nodes(h);
540 delete_all_nodes(h2);
541}
542
543TEST(SortUtilsHelpers, insert_sorted_htlist_and_list_insertion_sort)
544{
546 l.append(0);
547 l.append(2);
548
549 auto * node = new Snodenc<int>(1);
551 insert_sorted(l, static_cast<Slinknc *>(node), cmp);
552 EXPECT_TRUE(is_sorted(l));
553
555 for (int x : {3, 1, 2, 0})
556 l2.append(x);
557 list_insertion_sort<HTList, Compare_Snodenc<int, Aleph::less<int>>>(
558 static_cast<HTList &>(l2), cmp);
559 EXPECT_TRUE(is_sorted(l2));
560}
561
562TEST(SortUtilsHelpers, dlink_random_search_and_dlink_random_select)
563{
564 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
565 Dlink & base = static_cast<Dlink &>(h);
566
569
570 auto * found = dlink_random_search(base, 3, cmp);
571 ASSERT_NE(found, nullptr);
572 EXPECT_EQ(found->get_data(), 3);
573
574 auto * sel = dlink_random_select(base, 0, cmp);
575 ASSERT_NE(sel, nullptr);
576 EXPECT_EQ(static_cast<Dnode<int> *>(sel)->get_data(), 0);
577
578 delete_all_nodes(h);
579}
580
581TEST(SortUtilsHelpers, binindex_explicit)
582{
583 const auto a = make_dynarray({0, 1, 1, 1, 2, 3});
584 EXPECT_EQ(binindex(a, 2), 4);
585}
586
587TEST(SortUtilsHelpers, __random_select_raw_pointer)
588{
589 int a[] = {4, 1, 3, 2, 0, 2};
590 std::vector<int> expected(std::begin(a), std::end(a));
591 std::sort(expected.begin(), expected.end());
592
594 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 0, 0, 5, cmp)), expected[0]);
595 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 3, 0, 5, cmp)), expected[3]);
596 EXPECT_EQ((Aleph::__random_select<int, Aleph::less<int>>(a, 5, 0, 5, cmp)), expected[5]);
597}
598
599TEST(SortUtilsHelpers, sift_up_and_sift_down_restore_min_heap)
600{
602
603 // sift_up: insert new element at end and bubble up
604 {
606 a.reserve(4);
607 a(0) = 1;
608 a(1) = 3;
609 a(2) = 5;
610 a(3) = 0;
611 sift_up<int, Aleph::less<int>>(a, 4, cmp);
612 EXPECT_TRUE(is_min_heap(a, 4));
613 }
614
615 // sift_down: restore heap after root replaced
616 {
618 a.reserve(4);
619 a(0) = 3;
620 a(1) = 1;
621 a(2) = 2;
622 a(3) = 0; // outside heap when n=3
623 sift_down<int, Aleph::less<int>>(a, 3, cmp);
624 EXPECT_TRUE(is_min_heap(a, 3));
625 }
626}
627
628TEST(SortUtilsArraySorts, mergesort_pointer)
629{
630 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
631 mergesort(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
632 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
633}
634
635TEST(SortUtilsArraySorts, quicksort_pointer)
636{
637 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
638 quicksort(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
639 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
640}
641
642TEST(SortUtilsArraySorts, quicksort_rec_pointer)
643{
644 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
645 quicksort_rec(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
646 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
647}
648
649TEST(SortUtilsArraySorts, quicksort_rec_min_pointer)
650{
651 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
652 quicksort_rec_min(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
653 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
654}
655
656TEST(SortUtilsArraySorts, quicksort_insertion_pointer)
657{
658 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
659 quicksort_insertion(a, 0, static_cast<int>((sizeof(a) / sizeof(a[0])) - 1));
660 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
661
662 int b[] = {2, 1};
663 quicksort_insertion(b, 0, 1);
664 EXPECT_TRUE(std::is_sorted(std::begin(b), std::end(b)));
665}
666
667// Introsort tests - hybrid algorithm with O(n log n) guaranteed
668TEST(SortUtilsArraySorts, introsort_pointer_basic)
669{
670 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
671 introsort(a, 0L, static_cast<long>((sizeof(a) / sizeof(a[0])) - 1));
672 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
673}
674
675TEST(SortUtilsArraySorts, introsort_pointer_convenience)
676{
677 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
678 introsort(a, sizeof(a) / sizeof(a[0]));
679 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
680}
681
682TEST(SortUtilsArraySorts, introsort_pointer_custom_compare)
683{
684 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
685 introsort(a, 0L, 8L, std::greater<int>());
686 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a), std::greater<int>()));
687}
688
689TEST(SortUtilsArraySorts, introsort_dynarray)
690{
691 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
692 introsort(a);
693 for (size_t i = 1; i < a.size(); ++i)
694 ASSERT_LE(a(i - 1), a(i));
695}
696
697TEST(SortUtilsArraySorts, introsort_empty_and_single)
698{
699 // Empty array
700 int empty[] = {0};
701 introsort(empty, 0);
702 EXPECT_EQ(empty[0], 0);
703
704 // Single element
705 int single[] = {42};
706 introsort(single, 1);
707 EXPECT_EQ(single[0], 42);
708
709 // Empty DynArray
710 DynArray<int> da;
711 EXPECT_NO_THROW(introsort(da));
712}
713
714TEST(SortUtilsArraySorts, introsort_already_sorted)
715{
716 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
717 introsort(a, sizeof(a) / sizeof(a[0]));
718 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
719}
720
721TEST(SortUtilsArraySorts, introsort_reverse_sorted)
722{
723 int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
724 introsort(a, sizeof(a) / sizeof(a[0]));
725 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
726}
727
728TEST(SortUtilsArraySorts, introsort_all_equal)
729{
730 int a[] = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
731 introsort(a, sizeof(a) / sizeof(a[0]));
732 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
733}
734
735TEST(SortUtilsArraySorts, introsort_large_array_forces_heapsort)
736{
737 // Create an array large enough that might trigger heapsort fallback
738 // This tests the depth limit mechanism
739 const size_t n = 10000;
740 std::vector<int> v(n);
741 for (size_t i = 0; i < n; ++i)
742 v[i] = static_cast<int>(n - i); // Reverse sorted (worst case for quicksort)
743
744 introsort(v.data(), n);
745 EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));
746}
747
748TEST(SortUtilsArraySorts, introsort_dynarray_large)
749{
750 // Test with larger DynArray
751 const size_t n = 5000;
753 a.reserve(n);
754 for (size_t i = 0; i < n; ++i)
755 a(i) = static_cast<int>(n - i); // Reverse sorted
756
757 introsort(a);
758 for (size_t i = 1; i < n; ++i)
759 ASSERT_LE(a(i - 1), a(i)) << "Failed at index " << i;
760}
761
762// Introsort with STL-style pointer interface (begin, end)
763TEST(SortUtilsArraySorts, introsort_pointer_begin_end)
764{
765 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
766 introsort(a, a + 10); // STL-style: introsort(begin, end)
767 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
768}
769
770TEST(SortUtilsArraySorts, introsort_pointer_begin_end_partial)
771{
772 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
773 // Sort only middle portion [2, 7)
774 introsort(a + 2, a + 7);
775 // Elements 0,1 unchanged, 2-6 sorted, 7-9 unchanged
776 EXPECT_EQ(a[0], 9);
777 EXPECT_EQ(a[1], 1);
778 EXPECT_TRUE(std::is_sorted(a + 2, a + 7));
779 EXPECT_EQ(a[7], 4);
780}
781
782TEST(SortUtilsArraySorts, introsort_pointer_begin_end_custom_compare)
783{
784 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
785 introsort(a, a + 9, std::greater<int>());
786 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a), std::greater<int>()));
787}
788
789TEST(SortUtilsArraySorts, introsort_pointer_begin_end_empty)
790{
791 int a[] = {42};
792 // Empty range - should not crash
793 introsort(a, a);
794 EXPECT_EQ(a[0], 42); // Unchanged
795}
796
797// Introsort for Array<T> container
798TEST(SortUtilsArraySorts, introsort_array_container)
799{
800 Array<int> arr;
801 arr.append(5);
802 arr.append(2);
803 arr.append(8);
804 arr.append(1);
805 arr.append(9);
806 arr.append(3);
807
808 introsort(arr);
809
810 for (size_t i = 1; i < arr.size(); ++i)
811 ASSERT_LE(arr(i - 1), arr(i));
812}
813
814TEST(SortUtilsArraySorts, introsort_array_container_custom_compare)
815{
816 Array<int> arr;
817 for (int i = 1; i <= 10; ++i)
818 arr.append(i);
819
820 introsort(arr, std::greater<int>());
821
822 for (size_t i = 1; i < arr.size(); ++i)
823 ASSERT_GE(arr(i - 1), arr(i)); // Descending order
824}
825
826TEST(SortUtilsArraySorts, introsort_array_container_empty)
827{
828 Array<int> arr;
829 EXPECT_NO_THROW(introsort(arr));
830 EXPECT_TRUE(arr.is_empty());
831}
832
833TEST(SortUtilsArraySorts, introsort_array_container_single)
834{
835 Array<int> arr;
836 arr.append(42);
837 introsort(arr);
838 EXPECT_EQ(arr.size(), 1u);
839 EXPECT_EQ(arr(0), 42);
840}
841
842TEST(SortUtilsArraySorts, introsort_array_container_large)
843{
844 const size_t n = 5000;
845 auto arr = Array<int>::create_reserved(n);
846 for (size_t i = 0; i < n; ++i)
847 arr.append(static_cast<int>(n - i)); // Reverse sorted
848
849 introsort(arr);
850
851 for (size_t i = 1; i < n; ++i)
852 ASSERT_LE(arr(i - 1), arr(i)) << "Failed at index " << i;
853}
854
855// introsort() is pattern-defeating quicksort. These tests cover the
856// patterns that it detects, the sizes around its thresholds (24 items,
857// blocks of 64, 128 for the median of nine), its two partitions, its two
858// ways of reading the pivot (a copy of a trivially copyable item, and a
859// reference to the others), and what a comparison that throws leaves
860
861namespace
862{
863 // n keys with the named pattern
864 vector<int> pdq_keys(const string & pattern, const size_t n, const unsigned seed)
865 {
866 mt19937 rng(seed);
867 vector<int> keys(n);
868 const int m = static_cast<int>(n);
869 for (int i = 0; i < m; ++i)
870 if (pattern == "random")
871 keys[i] = static_cast<int>(rng() % (n + 1));
872 else if (pattern == "few")
873 keys[i] = static_cast<int>(rng() % 4);
874 else if (pattern == "equal")
875 keys[i] = 7;
876 else if (pattern == "reversed")
877 keys[i] = m - i;
878 else if (pattern == "organ")
879 keys[i] = i < m / 2 ? i : m - i;
880 else if (pattern == "sawtooth")
881 keys[i] = i % 17;
882 else // sorted, or nearly
883 keys[i] = i;
884 if (pattern == "nearly") // sorted, with a few items swapped
885 for (size_t k = 0; n > 1 and k < n / 50 + 1; ++k)
886 {
887 const size_t x = rng() % n;
888 const size_t y = rng() % n;
889 std::swap(keys[x], keys[y]);
890 }
891 return keys;
892 }
893
894 const vector<string> pdq_patterns = {"random", "few", "equal", "sorted", "reversed",
895 "organ", "sawtooth", "nearly"};
896
897 const vector<size_t> pdq_sizes = {0, 1, 2, 3, 5, 23, 24, 25, 63, 64, 65, 127, 128, 129,
898 130, 200, 1000, 5000, 40000};
899
900 // The comparison throws at each of the comparisons of a sort of items,
901 // in steps, and the items must stay in the array
902 template <typename T>
903 void introsort_keeps_the_items(const vector<T> & items)
904 {
905 size_t total = 0; // the comparisons of a sort that does not throw
906 {
907 auto a = items;
908 introsort(a.data(), a.size(), [&total](const T & x, const T & y)
909 {
910 ++total;
911 return x < y;
912 });
913 }
914 auto expected = items;
915 std::sort(expected.begin(), expected.end());
916 for (size_t k = 1; k <= total; k += std::max<size_t>(1, total / 400))
917 {
918 auto a = items;
919 size_t count = 0;
920 auto cmp = [&count, k](const T & x, const T & y)
921 {
922 if (++count == k)
923 throw runtime_error("comparison failed");
924 return x < y;
925 };
926 EXPECT_THROW(introsort(a.data(), a.size(), cmp), runtime_error);
927 std::sort(a.begin(), a.end());
928 ASSERT_EQ(a, expected) << "at comparison " << k;
929 }
930 }
931}
932
933TEST(SortUtilsArraySorts, introsort_gives_the_order_of_std_sort_on_every_pattern)
934{
935 for (const auto & pattern : pdq_patterns)
936 for (const size_t n : pdq_sizes)
937 {
938 auto a = pdq_keys(pattern, n, 1);
939 auto expected = a;
940 std::sort(expected.begin(), expected.end());
941 introsort(a.data(), n);
942 ASSERT_EQ(a, expected) << pattern << ", " << n << " items";
943
944 auto d = pdq_keys(pattern, n, 1);
945 std::sort(expected.begin(), expected.end(), std::greater<int>());
946 introsort(d.data(), n, std::greater<int>());
947 ASSERT_EQ(d, expected) << pattern << ", " << n << " items, descending";
948 }
949}
950
951TEST(SortUtilsArraySorts, introsort_sorts_pointers_by_their_targets)
952{
953 for (const auto & pattern : pdq_patterns)
954 for (const size_t n : pdq_sizes)
955 {
956 const auto keys = pdq_keys(pattern, n, 2);
957 vector<const int *> p(n);
958 for (size_t i = 0; i < n; ++i)
959 p[i] = &keys[i];
960 introsort(p.data(), n, [](const int * x, const int * y) { return *x < *y; });
961
962 auto expected = keys;
963 std::sort(expected.begin(), expected.end());
964 for (size_t i = 0; i < n; ++i)
965 ASSERT_EQ(*p[i], expected[i]) << pattern << ", " << n << " items";
966 std::sort(p.begin(), p.end()); // by address: each key once
967 for (size_t i = 0; i < n; ++i)
968 ASSERT_EQ(p[i], &keys[i]) << pattern << ", " << n << " items";
969 }
970}
971
972TEST(SortUtilsArraySorts, introsort_sorts_strings)
973{
974 for (const auto & pattern : pdq_patterns)
975 for (const size_t n : {size_t(0), size_t(1), size_t(24), size_t(129), size_t(1000),
976 size_t(5000)})
977 {
978 vector<string> a;
979 for (const int k : pdq_keys(pattern, n, 3))
980 a.push_back(to_string(k)); // in the order of strings, not of numbers
981 auto expected = a;
982 std::sort(expected.begin(), expected.end());
983 introsort(a.data(), n);
984 ASSERT_EQ(a, expected) << pattern << ", " << n << " items";
985 }
986}
987
988TEST(SortUtilsArraySorts, introsort_sorts_items_that_can_only_move)
989{
990 vector<unique_ptr<int>> a;
991 vector<int *> items;
992 for (const int k : pdq_keys("random", 3000, 4))
993 {
994 a.push_back(make_unique<int>(k));
995 items.push_back(a.back().get());
996 }
997 introsort(a.data(), a.size(),
998 [](const unique_ptr<int> & x, const unique_ptr<int> & y) { return *x < *y; });
999 for (size_t i = 1; i < a.size(); ++i)
1000 ASSERT_LE(*a[i - 1], *a[i]);
1001
1002 vector<int *> sorted_items;
1003 for (const auto & p : a)
1004 sorted_items.push_back(p.get());
1005 std::sort(items.begin(), items.end());
1006 std::sort(sorted_items.begin(), sorted_items.end());
1007 EXPECT_EQ(sorted_items, items);
1008}
1009
1010TEST(SortUtilsArraySorts, introsort_sorts_only_its_range)
1011{
1012 for (const size_t n : {size_t(24), size_t(200), size_t(5000)})
1013 {
1014 auto keys = pdq_keys("random", n, 5);
1015 vector<int> a(n + 20, numeric_limits<int>::max()); // the items before the range
1016 for (size_t i = n + 10; i < n + 20; ++i)
1017 a[i] = numeric_limits<int>::min(); // and those after it
1018 std::copy(keys.begin(), keys.end(), a.begin() + 10);
1019 introsort(a.data(), 10L, static_cast<long>(n + 9));
1020
1021 std::sort(keys.begin(), keys.end());
1022 EXPECT_TRUE(std::equal(keys.begin(), keys.end(), a.begin() + 10)) << n << " items";
1023 for (size_t i = 0; i < 10; ++i)
1024 {
1025 EXPECT_EQ(a[i], numeric_limits<int>::max());
1026 EXPECT_EQ(a[n + 10 + i], numeric_limits<int>::min());
1027 }
1028 }
1029}
1030
1031// A sorted range, one in descending order and one of equal items take a
1032// linear number of comparisons
1033TEST(SortUtilsArraySorts, introsort_takes_linear_comparisons_on_ordered_ranges)
1034{
1035 const size_t n = 100000;
1036 for (const string pattern : {"sorted", "reversed", "equal"})
1037 {
1038 auto a = pdq_keys(pattern, n, 6);
1039 size_t comparisons = 0;
1040 introsort(a.data(), n, [&comparisons](const int x, const int y)
1041 {
1042 ++comparisons;
1043 return x < y;
1044 });
1045 EXPECT_TRUE(std::is_sorted(a.begin(), a.end())) << pattern;
1046 EXPECT_LE(comparisons, 4 * n) << pattern;
1047 }
1048}
1049
1050// McIlroy's adversary ("A Killer Adversary for Quicksort", 1999) gives the
1051// items their values while the sort compares them, so that each partition
1052// is as unbalanced as it can be: a plain quicksort takes a quadratic
1053// number of comparisons, and introsort() must stay in O(n log n)
1054TEST(SortUtilsArraySorts, introsort_bounds_the_comparisons_of_a_killer_adversary)
1055{
1056 const int n = 20000;
1057 const int gas = n; // the value of an item not frozen yet, above all others
1058 vector<int> value(n, gas);
1059 int frozen = 0, candidate = 0;
1060 size_t comparisons = 0;
1061 auto cmp = [&](const int x, const int y)
1062 {
1063 ++comparisons;
1064 if (value[x] == gas and value[y] == gas)
1065 value[x == candidate ? x : y] = frozen++;
1066 if (value[x] == gas)
1067 candidate = x;
1068 else if (value[y] == gas)
1069 candidate = y;
1070 return value[x] < value[y];
1071 };
1072 vector<int> items(n);
1073 for (int i = 0; i < n; ++i)
1074 items[i] = i;
1075 introsort(items.data(), items.size(), cmp);
1076
1077 for (int i = 1; i < n; ++i)
1078 ASSERT_LE(value[items[i - 1]], value[items[i]]);
1079 EXPECT_LE(comparisons, static_cast<size_t>(3 * n * std::log2(n)));
1080}
1081
1082// If a comparison throws, the array keeps its items: those read through a
1083// copy of the pivot (int) and those read through a reference (string)
1084TEST(SortUtilsArraySorts, introsort_keeps_the_items_if_the_comparison_throws)
1085{
1086 for (const string pattern : {"random", "few", "sorted", "reversed", "organ", "nearly"})
1087 {
1088 const auto keys = pdq_keys(pattern, 600, 7);
1089 introsort_keeps_the_items(keys);
1090 vector<string> strings;
1091 for (const int k : keys)
1092 strings.push_back(to_string(k));
1093 introsort_keeps_the_items(strings);
1094 }
1095}
1096
1097// The heapsorts compare through Inversed_Compare, whose call was noexcept:
1098// a comparator that threw ended the program, also in the heapsort to which
1099// introsort() falls back. McIlroy's adversary ("A killer adversary for
1100// quicksort", 1999) decides the values as the sort compares them, so that
1101// the pivot is always among the least items and introsort() reaches its
1102// heapsort; the comparison throws at each of its comparisons, in steps
1103TEST(SortUtilsArraySorts, heapsorts_let_a_throwing_comparison_through)
1104{
1105 constexpr size_t n = 600;
1106 size_t count = 0, fail_at = 0;
1107 auto tick = [&count, &fail_at]
1108 {
1109 if (++count == fail_at)
1110 throw runtime_error("comparison failed");
1111 };
1112
1113 vector<int> val;
1114 int solid = 0, candidate = 0;
1115 const int gas = static_cast<int>(n);
1116 auto adversary = [&](const int x, const int y)
1117 {
1118 tick();
1119 if (val[x] == gas and val[y] == gas)
1120 val[x == candidate ? x : y] = solid++;
1121 if (val[x] == gas)
1122 candidate = x;
1123 else if (val[y] == gas)
1124 candidate = y;
1125 return val[x] < val[y];
1126 };
1127 auto sort_against_the_adversary = [&](const size_t k)
1128 {
1129 count = 0;
1130 fail_at = k;
1131 val.assign(n, gas);
1132 solid = candidate = 0;
1133 vector<int> a(n);
1134 for (size_t i = 0; i < n; ++i)
1135 a[i] = static_cast<int>(i);
1136 try
1137 {
1138 introsort(a.data(), a.size(), adversary);
1139 }
1140 catch (const runtime_error &)
1141 {
1142 std::sort(a.begin(), a.end());
1143 for (size_t i = 0; i < n; ++i)
1144 if (a[i] != static_cast<int>(i))
1145 return false;
1146 return true;
1147 }
1148 return false;
1149 };
1150
1151 (void) sort_against_the_adversary(0);
1152 const size_t total = count;
1153 for (size_t k = 1; k <= total; k += std::max<size_t>(1, total / 2000))
1154 ASSERT_TRUE(sort_against_the_adversary(k)) << "at comparison " << k << " of " << total;
1155
1156 auto throwing_less = [&tick](const int x, const int y)
1157 {
1158 tick();
1159 return x < y;
1160 };
1161 for (auto sort : {+[](int * a, size_t m, const decltype(throwing_less) & c) { heapsort(a, m, c); },
1162 +[](int * a, size_t m, const decltype(throwing_less) & c) { faster_heapsort(a, m, c); }})
1163 for (const size_t k : {size_t(1), size_t(50), size_t(500)})
1164 {
1165 vector<int> a = pdq_keys("random", 200, 3);
1166 count = 0;
1167 fail_at = k;
1168 EXPECT_THROW(sort(a.data(), a.size(), throwing_less), runtime_error) << "at comparison " << k;
1169 }
1170}
1171
1172TEST(SortUtilsArraySorts, heapsort_dynarray)
1173{
1174 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1175 heapsort(a);
1176 for (size_t i = 1; i < a.size(); ++i)
1177 ASSERT_LE(a(i - 1), a(i));
1178}
1179
1180TEST(SortUtilsArraySorts, quicksort_op_dynarray)
1181{
1182 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1183 quicksort_op(a);
1184 for (size_t i = 1; i < a.size(); ++i)
1185 ASSERT_LE(a(i - 1), a(i));
1186}
1187
1188TEST(SortUtilsArraySorts, quicksort_op_empty)
1189{
1190 DynArray<int> a;
1191 EXPECT_NO_THROW(quicksort_op(a));
1192 EXPECT_TRUE(a.is_empty());
1193}
1194
1195TEST(SortUtilsArraySorts, shellsort_dynarray)
1196{
1197 auto a = make_dynarray({9, 1, 8, 2, 7, 3, 6, 4, 5, 0});
1198 shellsort(a);
1199 for (size_t i = 1; i < a.size(); ++i)
1200 ASSERT_LE(a(i - 1), a(i));
1201}
1202
1203TEST(SortUtilsArraySorts, quicksort_dynarray)
1204{
1205 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1206 quicksort(a);
1207 for (size_t i = 1; i < a.size(); ++i)
1208 ASSERT_LE(a(i - 1), a(i));
1209}
1210
1211TEST(SortUtilsArraySorts, quicksort_rec_dynarray)
1212{
1213 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1214 quicksort_rec(a, 0, static_cast<long>(a.size() - 1));
1215 for (size_t i = 1; i < a.size(); ++i)
1216 ASSERT_LE(a(i - 1), a(i));
1217}
1218
1219// The sorts of a DynArray take as their pivot the median of the first,
1220// the middle and the last items: with the last item alone, a sorted or a
1221// reversed array made quicksort() and quicksort_rec() quadratic and sent
1222// introsort() to heapsort, and quicksort_op(), which moved the median
1223// alone to the last place, was quadratic on a reversed array
1224
1225namespace
1226{
1227 DynArray<int> dynarray_keys(const string & pattern, const size_t n)
1228 {
1229 mt19937 rng(10);
1230 DynArray<int> a;
1231 const int m = static_cast<int>(n);
1232 for (int i = 0; i < m; ++i)
1233 if (pattern == "random")
1234 a.append(static_cast<int>(rng() % (n + 1)));
1235 else if (pattern == "few")
1236 a.append(static_cast<int>(rng() % 4));
1237 else if (pattern == "reversed")
1238 a.append(m - i);
1239 else if (pattern == "organ")
1240 a.append(i < m / 2 ? i : m - i);
1241 else // sorted
1242 a.append(i);
1243 return a;
1244 }
1245
1246 // Sorts the keys of pattern with sort, checks that it gives the order
1247 // of std::sort, and returns the comparisons that it made
1248 template <class Sort>
1249 size_t sort_dynarray(const string & pattern, const size_t n, Sort sort)
1250 {
1251 auto a = dynarray_keys(pattern, n);
1252 vector<int> expected;
1253 for (size_t i = 0; i < n; ++i)
1254 expected.push_back(a(i));
1255 std::sort(expected.begin(), expected.end());
1256
1257 size_t comparisons = 0;
1258 sort(a, [&comparisons](const int x, const int y)
1259 {
1260 ++comparisons;
1261 return x < y;
1262 });
1263
1264 bool same = a.size() == n;
1265 for (size_t i = 0; same and i < n; ++i)
1266 same = a(i) == expected[i];
1267 EXPECT_TRUE(same) << pattern << ", " << n << " items";
1268 return comparisons;
1269 }
1270
1271 auto dynarray_introsort = [](DynArray<int> & a, const auto & cmp) { introsort(a, cmp); };
1272 auto dynarray_quicksort = [](DynArray<int> & a, const auto & cmp) { quicksort(a, cmp); };
1273 auto dynarray_quicksort_rec = [](DynArray<int> & a, const auto & cmp)
1274 {
1275 quicksort_rec(a, 0L, static_cast<long>(a.size()) - 1, cmp);
1276 };
1277 auto dynarray_quicksort_op = [](DynArray<int> & a, const auto & cmp) { quicksort_op(a, cmp); };
1278}
1279
1280TEST(SortUtilsArraySorts, sorts_of_a_dynarray_give_the_order_of_std_sort)
1281{
1282 for (const string pattern : {"random", "few", "sorted", "reversed", "organ"})
1283 for (const size_t n : {size_t(0), size_t(1), size_t(2), size_t(3), size_t(39), size_t(40),
1284 size_t(41), size_t(100), size_t(1000), size_t(3000)})
1285 {
1286 sort_dynarray(pattern, n, dynarray_introsort);
1287 sort_dynarray(pattern, n, dynarray_quicksort);
1288 sort_dynarray(pattern, n, dynarray_quicksort_rec);
1289 sort_dynarray(pattern, n, dynarray_quicksort_op);
1290 }
1291}
1292
1293TEST(SortUtilsArraySorts, sorts_of_a_dynarray_split_sorted_and_reversed_input_in_halves)
1294{
1295 const size_t n = 20000;
1296 const auto bound = static_cast<size_t>(2 * n * std::log2(n));
1297 for (const string pattern : {"sorted", "reversed"})
1298 {
1299 EXPECT_LE(sort_dynarray(pattern, n, dynarray_introsort), bound) << pattern;
1300 EXPECT_LE(sort_dynarray(pattern, n, dynarray_quicksort), bound) << pattern;
1301 EXPECT_LE(sort_dynarray(pattern, n, dynarray_quicksort_rec), bound) << pattern;
1302 EXPECT_LE(sort_dynarray(pattern, n, dynarray_quicksort_op), bound) << pattern;
1303 }
1304}
1305
1306TEST(SortUtilsListSorts, mergesort_dynlist)
1307{
1308 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1309 mergesort(l);
1310 EXPECT_TRUE(is_sorted(l));
1311}
1312
1313TEST(SortUtilsListSorts, mergeinsertsort_dynlist)
1314{
1315 DynList<int> l = make_dynlist({9, 8, 7, 6, 5, 4, 3, 2, 1, 0});
1317 EXPECT_TRUE(is_sorted(l));
1318}
1319
1320TEST(SortUtilsListSorts, insertion_sort_dynlist_rvalue)
1321{
1322 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1323 DynList<int> sorted = insertion_sort(std::move(l));
1324 EXPECT_TRUE(is_sorted(sorted));
1325 EXPECT_TRUE(l.is_empty());
1326}
1327
1328TEST(SortUtilsListSorts, mergesort_dynlist_rvalue)
1329{
1330 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1331 DynList<int> sorted = mergesort(std::move(l));
1332 EXPECT_TRUE(is_sorted(sorted));
1333 EXPECT_TRUE(l.is_empty());
1334}
1335
1336TEST(SortUtilsListSorts, quicksort_dynlist)
1337{
1338 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1339 quicksort(l);
1340 EXPECT_TRUE(is_sorted(l));
1341 EXPECT_EQ(l.get_first(), 0);
1342 EXPECT_EQ(l.get_last(), 4);
1343}
1344
1345TEST(SortUtilsListSorts, merge_lists_dynlist)
1346{
1347 DynList<int> l1 = make_dynlist({0, 2, 4});
1348 DynList<int> l2 = make_dynlist({1, 3, 5});
1350
1352 EXPECT_TRUE(l1.is_empty());
1353 EXPECT_TRUE(l2.is_empty());
1354 EXPECT_TRUE(is_sorted(out));
1355 EXPECT_EQ(out.size(), 6u);
1356 EXPECT_EQ(out.get_first(), 0);
1357 EXPECT_EQ(out.get_last(), 5);
1358}
1359
1360TEST(SortUtilsListSorts, merge_lists_dnode)
1361{
1362 auto l1 = make_dnode_list({0, 2, 4});
1363 auto l2 = make_dnode_list({1, 3, 5});
1365
1367
1368 EXPECT_TRUE(l1.is_empty());
1369 EXPECT_TRUE(l2.is_empty());
1370 EXPECT_FALSE(out.is_empty());
1371
1372 int expected = 0;
1373 for (Dnode<int>::Iterator it(out); it.has_curr(); it.next_ne(), ++expected)
1374 EXPECT_EQ(it.get_curr_ne()->get_data(), expected);
1375 EXPECT_EQ(expected, 6);
1376
1377 delete_all_nodes(out);
1378}
1379
1380TEST(SortUtilsDyndlistSorts, mergesort_dyndlist)
1381{
1382 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1383 mergesort(l);
1384 EXPECT_TRUE(is_sorted(l));
1385}
1386
1387namespace
1388{
1389 // An item whose order is that of its key alone; seq tells where it was
1390 struct Keyed { int key; int seq; };
1391
1392 struct By_Key
1393 {
1394 bool operator()(const Keyed & a, const Keyed & b) const noexcept
1395 {
1396 return a.key < b.key;
1397 }
1398 };
1399
1400 // Equal keys keep the order of their seq
1401 template <class Container>
1402 bool keeps_order_of_equals(const Container & c)
1403 {
1404 const Keyed * prev = nullptr;
1405 for (const Keyed & x : c)
1406 {
1407 if (prev != nullptr and prev->key == x.key and prev->seq > x.seq)
1408 return false;
1409 prev = &x;
1410 }
1411 return true;
1412 }
1413
1414 // The keys do not decrease
1415 template <class Container>
1416 bool sorted_by_key(const Container & c)
1417 {
1418 const Keyed * prev = nullptr;
1419 for (const Keyed & x : c)
1420 {
1421 if (prev != nullptr and By_Key()(x, *prev))
1422 return false;
1423 prev = &x;
1424 }
1425 return true;
1426 }
1427}
1428
1429// mergesort() is documented as stable, but, with equal keys, its merges
1430// took first the item of the second half, on lists and on arrays
1431TEST(SortUtilsStability, mergesort_keeps_the_order_of_equal_items)
1432{
1433 std::mt19937 gen(3);
1434 for (int round = 0; round < 50; ++round)
1435 {
1436 SCOPED_TRACE(round);
1437 std::vector<Keyed> items;
1438 const int n = 2 + int(gen() % 300);
1439 for (int i = 0; i < n; ++i)
1440 items.push_back({int(gen() % 7), i});
1441
1442 DynList<Keyed> list;
1443 DynDlist<Keyed> dlist;
1444 for (const Keyed & x : items)
1445 {
1446 list.append(x);
1447 dlist.append(x);
1448 }
1449 mergesort(list, By_Key());
1450 mergesort(dlist, By_Key());
1451 EXPECT_TRUE(sorted_by_key(list));
1452 EXPECT_TRUE(sorted_by_key(dlist));
1453 EXPECT_TRUE(keeps_order_of_equals(list));
1454 EXPECT_TRUE(keeps_order_of_equals(dlist));
1455
1456 std::vector<Keyed> array = items;
1457 mergesort(array.data(), 0, long(array.size()) - 1, By_Key());
1458 EXPECT_TRUE(keeps_order_of_equals(array));
1459 EXPECT_TRUE(std::is_sorted(array.begin(), array.end(), By_Key()));
1460 }
1461}
1462
1463namespace
1464{
1465 // Compares ints, and throws at the comparison number at
1466 struct Throws_At
1467 {
1468 int * count;
1469 int at;
1470
1471 bool operator()(const int a, const int b) const
1472 {
1473 if (++*count == at)
1474 throw std::runtime_error("comparison failed");
1475 return a < b;
1476 }
1477 };
1478
1479 // The items of c, sorted
1480 template <class Container>
1481 std::vector<int> sorted_items(const Container & c)
1482 {
1483 std::vector<int> v;
1484 for (const int x : c)
1485 v.push_back(x);
1486 std::sort(v.begin(), v.end());
1487 return v;
1488 }
1489}
1490
1491// mergesort() of a list promises that, if the comparison throws, the list
1492// keeps all its items; the comparison throws here at each of the ones that
1493// the sort makes
1494TEST(SortUtilsStability, mergesort_of_a_list_keeps_its_items_if_the_comparison_throws)
1495{
1496 std::mt19937 gen(11);
1497 std::vector<int> items;
1498 for (int i = 0; i < 60; ++i)
1499 items.push_back(int(gen() % 20));
1500 const std::vector<int> all = sorted_items(items);
1501
1502 int total = 0; // the comparisons of a sort that does not throw
1503 {
1504 DynList<int> list;
1505 for (const int x : items)
1506 list.append(x);
1507 mergesort(list, Throws_At{&total, -1});
1508 ASSERT_EQ(sorted_items(list), all);
1509 }
1510 ASSERT_GT(total, 0);
1511
1512 for (int at = 1; at <= total; ++at)
1513 {
1514 SCOPED_TRACE(at);
1515 DynList<int> list;
1516 DynDlist<int> dlist;
1517 for (const int x : items)
1518 {
1519 list.append(x);
1520 dlist.append(x);
1521 }
1522
1523 int count = 0;
1524 EXPECT_THROW(mergesort(list, Throws_At{&count, at}), std::runtime_error);
1525 count = 0;
1526 EXPECT_THROW(mergesort(dlist, Throws_At{&count, at}), std::runtime_error);
1527
1528 EXPECT_EQ(sorted_items(list), all);
1529 EXPECT_EQ(sorted_items(dlist), all);
1530 }
1531}
1532
1533namespace
1534{
1535 // sort(list, cmp) sorts list with cmp. If cmp throws, at each of its
1536 // calls, list must keep its items.
1537 template <class List, class Sort>
1538 void keeps_its_items_if_the_comparison_throws(const std::vector<int> & items,
1539 Sort sort)
1540 {
1541 const std::vector<int> all = sorted_items(items);
1542 int total = 0; // the comparisons of a sort that does not throw
1543 {
1544 List list;
1545 for (const int x : items)
1546 list.append(x);
1547 sort(list, Throws_At{&total, -1});
1548 std::vector<int> got;
1549 for (const int x : list)
1550 got.push_back(x);
1551 ASSERT_EQ(got, all); // sorted
1552 }
1553 ASSERT_GT(total, 0);
1554
1555 for (int at = 1; at <= total; ++at)
1556 {
1557 SCOPED_TRACE(at);
1558 List list;
1559 for (const int x : items)
1560 list.append(x);
1561 int count = 0;
1562 EXPECT_THROW(sort(list, Throws_At{&count, at}), std::runtime_error);
1563 EXPECT_EQ(sorted_items(list), all);
1564 }
1565 }
1566}
1567
1568// The template of templates of mergesort() and mergeinsertsort() had no
1569// handler, nor had the insertion sort of the short lists of
1570// mergeinsertsort(), whose nodes were then in a list that did not own them
1571TEST(SortUtilsStability, every_sort_of_a_list_keeps_its_items_if_the_comparison_throws)
1572{
1573 std::mt19937 gen(13);
1574 std::vector<int> items; // more than Insertion_Threshold
1575 for (int i = 0; i < 100; ++i)
1576 items.push_back(int(gen() % 20));
1577
1578 {
1579 SCOPED_TRACE("mergesort<DynList, int>()");
1580 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (auto & l, const Throws_At & c)
1581 {
1582 mergesort<DynList, int, Throws_At>(l, c);
1583 });
1584 }
1585 {
1586 SCOPED_TRACE("mergesort<DynDlist, int>()");
1587 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (auto & l, const Throws_At & c)
1588 {
1589 mergesort<DynDlist, int, Throws_At>(l, c);
1590 });
1591 }
1592 {
1593 SCOPED_TRACE("mergeinsertsort(DynList &)");
1594 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (auto & l, const Throws_At & c)
1595 {
1596 mergeinsertsort(l, c);
1597 });
1598 }
1599 {
1600 SCOPED_TRACE("mergeinsertsort(DynDlist &)");
1601 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (auto & l, const Throws_At & c)
1602 {
1603 mergeinsertsort(l, c);
1604 });
1605 }
1606 {
1607 SCOPED_TRACE("insertion_sort(DynList &)");
1608 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (auto & l, const Throws_At & c)
1609 {
1610 insertion_sort(l, c);
1611 });
1612 }
1613 {
1614 SCOPED_TRACE("insertion_sort(DynDlist &)");
1615 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (auto & l, const Throws_At & c)
1616 {
1617 insertion_sort(l, c);
1618 });
1619 }
1620}
1621
1622// insertion_sort() of a DynDlist took the template of the arrays, and did
1623// not compile; the insertion is stable
1624TEST(SortUtilsStability, insertion_sort_of_a_dyndlist_keeps_the_order_of_equal_items)
1625{
1626 std::mt19937 gen(5);
1627 for (int n = 0; n <= 60; ++n)
1628 {
1629 SCOPED_TRACE(n);
1630 DynDlist<Keyed> dlist;
1631 DynList<Keyed> list;
1632 for (int i = 0; i < n; ++i)
1633 {
1634 const Keyed x{int(gen() % 5), i};
1635 dlist.append(x);
1636 list.append(x);
1637 }
1638 insertion_sort(dlist, By_Key());
1639 insertion_sort(list, By_Key());
1640 EXPECT_TRUE(sorted_by_key(dlist));
1641 EXPECT_TRUE(keeps_order_of_equals(dlist));
1642 EXPECT_TRUE(sorted_by_key(list));
1643 EXPECT_TRUE(keeps_order_of_equals(list));
1644 EXPECT_EQ(dlist.size(), size_t(n));
1645 }
1646}
1647
1648namespace
1649{
1650 // Compares strings, and throws at the comparison number at
1651 struct Strings_Throw_At
1652 {
1653 int * count;
1654 int at;
1655
1656 bool operator()(const std::string & a, const std::string & b) const
1657 {
1658 if (++*count == at)
1659 throw std::runtime_error("comparison failed");
1660 return a < b;
1661 }
1662 };
1663}
1664
1665// merge() of an array moved its left part to a buffer: if the comparison
1666// threw, what was left there did not go back, and the array kept the
1667// strings that had been moved from, which are empty
1668TEST(SortUtilsStability, mergesort_of_an_array_keeps_its_items_if_the_comparison_throws)
1669{
1670 std::vector<std::string> items;
1671 for (int i = 0; i < 64; ++i)
1672 items.push_back("item " + std::to_string(i * 37 % 64));
1673 std::vector<std::string> all = items;
1674 std::sort(all.begin(), all.end());
1675
1676 int total = 0; // the comparisons of a sort that does not throw
1677 {
1678 std::vector<std::string> a = items;
1679 mergesort(a.data(), 0, long(a.size()) - 1, Strings_Throw_At{&total, -1});
1680 ASSERT_EQ(a, all);
1681 }
1682 ASSERT_GT(total, 0);
1683
1684 for (int at = 1; at <= total; ++at)
1685 {
1686 SCOPED_TRACE(at);
1687 std::vector<std::string> a = items;
1688 int count = 0;
1689 EXPECT_THROW(mergesort(a.data(), 0, long(a.size()) - 1, Strings_Throw_At{&count, at}),
1690 std::runtime_error);
1691 std::sort(a.begin(), a.end());
1692 EXPECT_EQ(a, all);
1693 }
1694}
1695
1696namespace
1697{
1698 // An int whose <, which does not say noexcept, throws at the comparison
1699 // number at; a sort compares it with its default comparison, Aleph::less
1700 struct Throwing_Less
1701 {
1702 static inline int count = 0;
1703 static inline int at = 0;
1704 int value;
1705
1706 bool operator < (const Throwing_Less & other) const
1707 {
1708 if (++count == at)
1709 throw std::runtime_error("comparison failed");
1710 return value < other.value;
1711 }
1712 };
1713
1714 template <class Container>
1715 std::vector<int> sorted_values(const Container & c)
1716 {
1717 std::vector<int> v;
1718 for (const Throwing_Less & x : c)
1719 v.push_back(x.value);
1720 std::sort(v.begin(), v.end());
1721 return v;
1722 }
1723}
1724
1725static_assert(not noexcept(Aleph::less<Throwing_Less>()(std::declval<const Throwing_Less &>(),
1726 std::declval<const Throwing_Less &>())));
1727
1728// Aleph::less was noexcept whatever the < of its type, so that a sort that
1729// compared with it took its merges for ones that cannot throw: they had no
1730// handler, and a < that threw ended the program
1731TEST(SortUtilsStability, what_the_less_than_of_the_items_throws_reaches_the_caller)
1732{
1733 std::vector<int> values;
1734 for (int i = 0; i < 50; ++i)
1735 values.push_back(i * 17 % 50);
1736 const std::vector<int> all = sorted_items(values);
1737
1738 Throwing_Less::count = 0;
1739 Throwing_Less::at = 0;
1740 {
1742 for (const int v : values)
1743 list.append(Throwing_Less{v});
1744 mergesort(list);
1745 ASSERT_EQ(sorted_values(list), all);
1746 }
1747 const int total = Throwing_Less::count;
1748 ASSERT_GT(total, 0);
1749
1750 for (int at = 1; at <= total; ++at)
1751 {
1752 SCOPED_TRACE(at);
1755 std::vector<Throwing_Less> array;
1756 for (const int v : values)
1757 {
1758 list.append(Throwing_Less{v});
1759 dlist.append(Throwing_Less{v});
1760 array.push_back(Throwing_Less{v});
1761 }
1762
1763 Throwing_Less::count = 0;
1764 Throwing_Less::at = at;
1765 EXPECT_THROW(mergesort(list), std::runtime_error);
1766 Throwing_Less::count = 0;
1767 EXPECT_THROW(mergesort(dlist), std::runtime_error);
1768 Throwing_Less::count = 0;
1769 EXPECT_THROW(mergesort(array.data(), 0, long(array.size()) - 1), std::runtime_error);
1770 Throwing_Less::at = 0;
1771
1772 EXPECT_EQ(sorted_values(list), all);
1773 EXPECT_EQ(sorted_values(dlist), all);
1774 EXPECT_EQ(sorted_values(array), all);
1775 }
1776}
1777
1778TEST(SortUtilsDyndlistSorts, search_extreme_min)
1779{
1780 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1781 int * p = search_extreme(l);
1782 ASSERT_NE(p, nullptr);
1783 EXPECT_EQ(*p, 0);
1784}
1785
1786TEST(SortUtilsDyndlistSorts, random_select_dyndlist)
1787{
1788 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1789 int * p = random_select(l, 0);
1790 ASSERT_NE(p, nullptr);
1791 EXPECT_EQ(*p, 0);
1792
1793 p = random_select(l, 5);
1794 ASSERT_NE(p, nullptr);
1795 EXPECT_EQ(*p, 4);
1796}
1797
1798TEST(SortUtilsDyndlistSorts, random_search_dyndlist)
1799{
1800 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1801
1802 int * p = random_search(l, 3);
1803 ASSERT_NE(p, nullptr);
1804 EXPECT_EQ(*p, 3);
1805
1806 p = random_search(l, 99);
1807 EXPECT_EQ(p, nullptr);
1808}
1809
1810TEST(SortUtilsDnodeDlinkAlgorithms, random_select_and_random_search_on_dlink)
1811{
1812 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1813
1814 auto * n0 = random_select<int>(h, 0);
1815 ASSERT_NE(n0, nullptr);
1816 EXPECT_EQ(n0->get_data(), 0);
1817
1818 auto * nmax = random_select<int>(h, 5);
1819 ASSERT_NE(nmax, nullptr);
1820 EXPECT_EQ(nmax->get_data(), 4);
1821
1822 auto * nfound = random_search<int>(h, 3);
1823 ASSERT_NE(nfound, nullptr);
1824 EXPECT_EQ(nfound->get_data(), 3);
1825
1826 auto * nmiss = random_search<int>(h, 99);
1827 EXPECT_EQ(nmiss, nullptr);
1828
1829 delete_all_nodes(h);
1830}
1831
1832TEST(SortUtilsHTListPath, quicksort_htlist_via_dynlist)
1833{
1834 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1835 quicksort<int>(static_cast<HTList &>(l), Aleph::less<int>());
1836 EXPECT_TRUE(is_sorted(l));
1837}
1838
1839TEST(SortUtilsSearchSequential, sequential_search_raw_array)
1840{
1841 int a[] = {4, 1, 3, 2, 0, 2};
1842 EXPECT_EQ(sequential_search(a, int{3}, 0, 5), 2);
1843 EXPECT_EQ(sequential_search(a, int{99}, 0, 5), Not_Found);
1844}
1845
1846TEST(SortUtilsSearchSequential, sequential_search_dynarray)
1847{
1848 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1849 EXPECT_EQ(sequential_search(a, 3, 0, static_cast<int>(a.size() - 1)), 2);
1850 EXPECT_EQ(sequential_search(a, 99, 0, static_cast<int>(a.size() - 1)), Not_Found);
1851}
1852
1853TEST(SortUtilsSearchSequential, sequential_search_dynlist)
1854{
1855 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1856 int * p = sequential_search(l, 3);
1857 ASSERT_NE(p, nullptr);
1858 EXPECT_EQ(*p, 3);
1859
1860 p = sequential_search(l, 99);
1861 EXPECT_EQ(p, nullptr);
1862}
1863
1864TEST(SortUtilsSearchSequential, sequential_search_const_dynlist)
1865{
1866 const DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1867 const int * p = sequential_search(l, 3);
1868 ASSERT_NE(p, nullptr);
1869 EXPECT_EQ(*p, 3);
1870
1871 p = sequential_search(l, 99);
1872 EXPECT_EQ(p, nullptr);
1873}
1874
1875TEST(SortUtilsSearchSequential, sequential_search_dyndlist)
1876{
1877 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1878 int * p = sequential_search(l, 3);
1879 ASSERT_NE(p, nullptr);
1880 EXPECT_EQ(*p, 3);
1881 p = sequential_search(l, 99);
1882 EXPECT_EQ(p, nullptr);
1883}
1884
1885TEST(SortUtilsSearchSequential, sequential_search_dnode)
1886{
1887 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1888
1889 auto * n = sequential_search(h, 3);
1890 ASSERT_NE(n, nullptr);
1891 EXPECT_EQ(n->get_data(), 3);
1892
1893 n = sequential_search(h, 99);
1894 EXPECT_EQ(n, nullptr);
1895
1896 delete_all_nodes(h);
1897}
1898
1899TEST(SortUtilsSearchExtreme, search_extreme_dnode_min)
1900{
1901 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1902 auto * n = search_extreme<int>(h, Aleph::less<int>());
1903 ASSERT_NE(n, nullptr);
1904 EXPECT_EQ(n->get_data(), 0);
1905 delete_all_nodes(h);
1906}
1907
1908TEST(SortUtilsSearchExtreme, search_min_max_raw_array)
1909{
1910 int a[] = {4, 1, 3, 2, 0, 2};
1911 EXPECT_EQ(search_min(a, 0, 5), 4);
1912 EXPECT_EQ(search_max(a, 0, 5), 0);
1913}
1914
1915TEST(SortUtilsSearchExtreme, search_extreme_and_search_max_dynarray)
1916{
1917 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
1918 EXPECT_EQ(search_extreme(a, 0, static_cast<long>(a.size() - 1)), 4);
1919 EXPECT_EQ(search_max(a, 0, static_cast<long>(a.size() - 1)), 0);
1920}
1921
1922TEST(SortUtilsSearchExtreme, search_min_max_dyndlist)
1923{
1924 DynDlist<int> l = make_dyndlist({4, 1, 3, 2, 0, 2});
1925 int * mn = search_min(l);
1926 int * mx = search_max(l);
1927 ASSERT_NE(mn, nullptr);
1928 ASSERT_NE(mx, nullptr);
1929 EXPECT_EQ(*mn, 0);
1930 EXPECT_EQ(*mx, 4);
1931}
1932
1933TEST(SortUtilsSearchExtreme, search_extreme_dynlist_min_max)
1934{
1935 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1936 int * mn = search_extreme(l);
1937 int * mx = search_extreme(l, Aleph::greater<int>());
1938 ASSERT_NE(mn, nullptr);
1939 ASSERT_NE(mx, nullptr);
1940 EXPECT_EQ(*mn, 0);
1941 EXPECT_EQ(*mx, 4);
1942}
1943
1944TEST(SortUtilsSearchExtreme, search_extreme_const_dynlist_min_max)
1945{
1946 const DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1947 const int * mn = search_extreme(l);
1948 const int * mx = search_extreme(l, Aleph::greater<int>());
1949 ASSERT_NE(mn, nullptr);
1950 ASSERT_NE(mx, nullptr);
1951 EXPECT_EQ(*mn, 0);
1952 EXPECT_EQ(*mx, 4);
1953
1954 const DynList<int> empty;
1955 EXPECT_EQ(search_extreme(empty), nullptr);
1956}
1957
1958TEST(SortUtilsSearchExtreme, search_min_max_dynlist)
1959{
1960 DynList<int> l = make_dynlist({4, 1, 3, 2, 0, 2});
1961 int * mn = search_extreme(l, Aleph::less<int>());
1962 int * mx = search_extreme(l, Aleph::greater<int>());
1963 ASSERT_NE(mn, nullptr);
1964 ASSERT_NE(mx, nullptr);
1965 EXPECT_EQ(*mn, 0);
1966 EXPECT_EQ(*mx, 4);
1967}
1968
1969TEST(SortUtilsDnodeSorts, selection_insertion_quick_merge)
1970{
1971 {
1972 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1974 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
1975 delete_all_nodes(h);
1976 }
1977
1978 {
1979 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1981 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
1982 delete_all_nodes(h);
1983 }
1984
1985 {
1986 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1987 quicksort(h);
1988 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
1989 delete_all_nodes(h);
1990 }
1991
1992 {
1993 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1994 mergesort(h);
1995 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
1996 delete_all_nodes(h);
1997 }
1998}
1999
2000TEST(SortUtilsDlinkSorts, quicksort_dlink)
2001{
2002 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
2003 Dlink & base = static_cast<Dlink &>(h);
2004
2006 quicksort(base, Cmp(Aleph::less<int>()));
2007
2008 EXPECT_EQ(search_extreme<int>(h, Aleph::less<int>())->get_data(), 0);
2009 EXPECT_EQ(search_extreme<int>(h, Aleph::greater<int>())->get_data(), 4);
2010
2011 delete_all_nodes(h);
2012}
2013
2014TEST(SortUtilsSearch, binary_search_dup_and_bsearch)
2015{
2016 auto a = make_dynarray({0, 1, 1, 1, 2, 3});
2017
2018 auto idxs = binary_search_dup(a, 1);
2019 ASSERT_EQ(idxs.size(), 3u);
2020 EXPECT_EQ(idxs.get_first(), 1u);
2021 EXPECT_EQ(idxs.get_last(), 3u);
2022
2023 int * p = bsearch(a, 1);
2024 ASSERT_NE(p, nullptr);
2025 EXPECT_EQ(*p, 1);
2026 EXPECT_EQ(bsearch(a, 99), nullptr);
2027}
2028
2029TEST(SortUtilsSearch, binary_search_dup_boundary_cases)
2030{
2031 {
2032 auto a = make_dynarray({1, 1, 1, 2, 3});
2033 auto idxs = binary_search_dup(a, 1);
2034 ASSERT_EQ(idxs.size(), 3u);
2035 EXPECT_EQ(idxs.get_first(), 0u);
2036 EXPECT_EQ(idxs.get_last(), 2u);
2037 }
2038
2039 {
2040 auto a = make_dynarray({0, 1, 2, 3, 3, 3});
2041 auto idxs = binary_search_dup(a, 3);
2042 ASSERT_EQ(idxs.size(), 3u);
2043 EXPECT_EQ(idxs.get_first(), 3u);
2044 EXPECT_EQ(idxs.get_last(), 5u);
2045 }
2046}
2047
2048TEST(SortUtilsSearch, binary_search_dup_custom_compare_descending)
2049{
2050 // Descending sorted with duplicates
2051 auto a = make_dynarray({5, 4, 3, 3, 3, 2, 1, 1, 0});
2052 auto idxs = binary_search_dup(a, 3, Aleph::greater<int>());
2053 ASSERT_EQ(idxs.size(), 3u);
2054 EXPECT_EQ(idxs.get_first(), 2u);
2055 EXPECT_EQ(idxs.get_last(), 4u);
2056
2057 idxs = binary_search_dup(a, 1, Aleph::greater<int>());
2058 ASSERT_EQ(idxs.size(), 2u);
2059 EXPECT_EQ(idxs.get_first(), 6u);
2060 EXPECT_EQ(idxs.get_last(), 7u);
2061}
2062
2063TEST(SortUtilsSearch, bsearch_dup_custom_compare_descending)
2064{
2065 auto a = make_dynarray({5, 4, 3, 3, 3, 2, 1, 1, 0});
2066 auto ps = bsearch_dup(a, 3, Aleph::greater<int>());
2067 ASSERT_EQ(ps.size(), 3u);
2068 for (auto p : ps)
2069 {
2070 ASSERT_NE(p, nullptr);
2071 EXPECT_EQ(*p, 3);
2072 }
2073}
2074
2075TEST(SortUtilsIndexBuild, build_index_and_build_index_ptr)
2076{
2077 auto a = make_dynarray({3, 1, 2, 1, 0});
2078
2079 auto idx = build_index(a);
2080
2081 static_assert(std::is_same_v<decltype(idx), Array<size_t>>);
2082 ASSERT_EQ(idx.size(), a.size());
2083 for (size_t i = 1; i < idx.size(); ++i)
2084 ASSERT_LE(a(idx(i - 1)), a(idx(i)));
2085
2086 auto ptrs = build_index_ptr(a);
2087 static_assert(std::is_same_v<decltype(ptrs), Array<int *>>);
2088 ASSERT_EQ(ptrs.size(), a.size());
2089 for (size_t i = 1; i < ptrs.size(); ++i)
2090 ASSERT_LE(*ptrs(i - 1), *ptrs(i));
2091
2092 const auto &ca = a;
2093 auto cptrs = build_index_ptr(ca);
2094 static_assert(std::is_same_v<decltype(cptrs), Array<const int *>>);
2095 ASSERT_EQ(cptrs.size(), a.size());
2096 for (size_t i = 1; i < cptrs.size(); ++i)
2097 ASSERT_LE(*cptrs(i - 1), *cptrs(i));
2098}
2099
2100TEST(SortUtilsIndexBuild, build_index_supports_std_vector)
2101{
2102 std::vector<int> a = {3, 1, 2, 1, 0};
2103
2104 auto idx = build_index(a);
2105
2106 static_assert(std::is_same_v<decltype(idx), Array<size_t>>);
2107 ASSERT_EQ(idx.size(), a.size());
2108 for (size_t i = 1; i < idx.size(); ++i)
2109 ASSERT_LE(a[idx(i - 1)], a[idx(i)]);
2110}
2111
2112TEST(SortUtilsIndexBuild, stable_build_index_preserves_equal_order_dynarray)
2113{
2114 auto a = make_dynarray({2, 1, 2, 1, 2});
2115
2116 auto idx = stable_build_index(a);
2117
2118 static_assert(std::is_same_v<decltype(idx), Array<size_t>>);
2119 ASSERT_EQ(idx.size(), a.size());
2120 EXPECT_EQ(idx(0), 1u);
2121 EXPECT_EQ(idx(1), 3u);
2122 EXPECT_EQ(idx(2), 0u);
2123 EXPECT_EQ(idx(3), 2u);
2124 EXPECT_EQ(idx(4), 4u);
2125}
2126
2127TEST(SortUtilsIndexBuild, stable_build_index_ptr_preserves_equal_order)
2128{
2129 auto a = make_dynarray({2, 1, 2, 1, 2});
2130
2131 auto ptrs = stable_build_index_ptr(a);
2132
2133 static_assert(std::is_same_v<decltype(ptrs), Array<int *>>);
2134 ASSERT_EQ(ptrs.size(), a.size());
2135 // Same stable order as stable_build_index's {1, 3, 0, 2, 4} on this
2136 // exact input, expressed as pointers into `a` instead of indices.
2137 EXPECT_EQ(ptrs(0), &a(1));
2138 EXPECT_EQ(ptrs(1), &a(3));
2139 EXPECT_EQ(ptrs(2), &a(0));
2140 EXPECT_EQ(ptrs(3), &a(2));
2141 EXPECT_EQ(ptrs(4), &a(4));
2142
2143 const auto &ca = a;
2144 auto cptrs = stable_build_index_ptr(ca);
2145 static_assert(std::is_same_v<decltype(cptrs), Array<const int *>>);
2146 ASSERT_EQ(cptrs.size(), a.size());
2147 for (size_t i = 0; i < ptrs.size(); ++i)
2148 EXPECT_EQ(cptrs(i), ptrs(i));
2149}
2150
2151TEST(SortUtilsIndexBuild, stable_build_index_ptr_preserves_large_duplicate_groups)
2152{
2153 DynArray<int> a;
2154 a.reserve(75);
2155 for (size_t i = 0; i < 75; ++i)
2156 a(i) = static_cast<int>((i * 17) % 5);
2157
2158 auto ptrs = stable_build_index_ptr(a);
2159
2160 static_assert(std::is_same_v<decltype(ptrs), Array<int *>>);
2161 ASSERT_EQ(ptrs.size(), a.size());
2162 for (size_t i = 1; i < ptrs.size(); ++i)
2163 {
2164 ASSERT_LE(*ptrs(i - 1), *ptrs(i));
2165 if (*ptrs(i - 1) == *ptrs(i))
2166 {
2167 EXPECT_LT(ptrs(i - 1), ptrs(i))
2168 << "equal-valued elements must keep their original relative order";
2169 }
2170 }
2171}
2172
2173TEST(SortUtilsIndexBuild, stable_build_index_preserves_large_duplicate_groups)
2174{
2175 std::vector<int> a;
2176 for (size_t i = 0; i < 75; ++i)
2177 a.push_back(static_cast<int>((i * 17) % 5));
2178
2179 auto idx = stable_build_index(a);
2180
2181 static_assert(std::is_same_v<decltype(idx), Array<size_t>>);
2182 ASSERT_EQ(idx.size(), a.size());
2183 for (size_t i = 1; i < idx.size(); ++i)
2184 {
2185 ASSERT_LE(a[idx(i - 1)], a[idx(i)]);
2186 if (a[idx(i - 1)] == a[idx(i)])
2187 {
2188 EXPECT_LT(idx(i - 1), idx(i));
2189 }
2190 }
2191}
2192
2193TEST(SortUtilsIndexBuild, stable_build_index_exhaustive_matches_stable_sort_reference)
2194{
2195 expect_stable_build_index_matches_reference_exhaustively(std::less<int>());
2196}
2197
2198TEST(SortUtilsIndexBuild, stable_build_index_exhaustive_matches_descending_stable_sort_reference)
2199{
2200 expect_stable_build_index_matches_reference_exhaustively(std::greater<int>());
2201}
2202
2203TEST(SortUtilsIndexBuild, stable_build_index_supports_std_vector)
2204{
2205 std::vector<int> a = {2, 1, 2, 1, 2};
2206
2207 auto idx = stable_build_index(a);
2208
2209 static_assert(std::is_same_v<decltype(idx), Array<size_t>>);
2210 ASSERT_EQ(idx.size(), a.size());
2211 EXPECT_EQ(idx(0), 1u);
2212 EXPECT_EQ(idx(1), 3u);
2213 EXPECT_EQ(idx(2), 0u);
2214 EXPECT_EQ(idx(3), 2u);
2215 EXPECT_EQ(idx(4), 4u);
2216}
2217
2218TEST(SortUtilsSlinkncPath, sequential_search_and_search_extreme_on_slinknc)
2219{
2220 Slinknc head;
2221 auto * n1 = new Snodenc<int>(4);
2222 auto * n2 = new Snodenc<int>(1);
2223 auto * n3 = new Snodenc<int>(3);
2224 auto * n4 = new Snodenc<int>(0);
2225 head.insert(n1);
2226 head.insert(n2);
2227 head.insert(n3);
2228 head.insert(n4);
2229
2230 auto found = sequential_search(head, 3);
2231 ASSERT_NE(found, nullptr);
2232 EXPECT_EQ(static_cast<Snodenc<int>*>(found)->get_data(), 3);
2233
2234 auto missing = sequential_search(head, 99);
2235 EXPECT_EQ(missing, nullptr);
2236
2237 auto extreme_min = search_extreme(head, Compare_Snodenc<int, Aleph::less<int>>(Aleph::less<int>()));
2238 ASSERT_NE(extreme_min, nullptr);
2239 EXPECT_EQ(static_cast<Snodenc<int>*>(extreme_min)->get_data(), 0);
2240
2241 while (not head.is_empty())
2242 delete static_cast<Snodenc<int>*>(head.remove_next());
2243}
2244
2245TEST(SortUtilsSlinkncPath, sequential_search_default_equal_on_slinknc)
2246{
2247 Slinknc head;
2248 auto * n1 = new Snodenc<int>(2);
2249 auto * n2 = new Snodenc<int>(1);
2250 auto * n3 = new Snodenc<int>(0);
2251 head.insert(n1);
2252 head.insert(n2);
2253 head.insert(n3);
2254
2255 auto * found = sequential_search<int>(head, 1);
2256 ASSERT_NE(found, nullptr);
2257 EXPECT_EQ(found->to_data<int>(), 1);
2258
2259 auto * missing = sequential_search<int>(head, 99);
2260 EXPECT_EQ(missing, nullptr);
2261
2262 while (not head.is_empty())
2263 delete static_cast<Snodenc<int>*>(head.remove_next());
2264}
2265
2266TEST(SortUtilsDlinkPath, sequential_search_and_selection_sort_on_dlink)
2267{
2268 auto h = make_dnode_list({3, 1, 2, 0});
2269 Dlink & base = static_cast<Dlink &>(h);
2270
2271 auto * found = sequential_search<int>(base, 2);
2272 ASSERT_NE(found, nullptr);
2273 EXPECT_EQ(static_cast<Dnode<int>*>(found)->get_data(), 2);
2274
2276 auto * mn = search_extreme<int>(h, Aleph::less<int>());
2277 ASSERT_NE(mn, nullptr);
2278 EXPECT_EQ(mn->get_data(), 0);
2279
2280 delete_all_nodes(h);
2281}
2282
2283TEST(SortUtilsRandomSearch, random_search_raw_and_dynarray)
2284{
2285 int a[] = {4, 1, 3, 2, 0, 2};
2286 int idx = random_search(a, 3, 0, 5);
2287 ASSERT_NE(idx, Not_Found);
2288 EXPECT_EQ(a[idx], 3);
2289 EXPECT_EQ(random_search(a, 99, 0, 5), Not_Found);
2290
2291 auto d = make_dynarray({4, 1, 3, 2, 0, 2});
2292 idx = random_search(d, 3, 0, static_cast<long>(d.size() - 1));
2293 ASSERT_NE(idx, Not_Found);
2294 EXPECT_EQ(d(idx), 3);
2295 EXPECT_EQ(random_search(d, 99, 0, static_cast<long>(d.size() - 1)), Not_Found);
2296}
2297
2298TEST(SortUtilsRandomSelect, random_select_array_container)
2299{
2300 Array<int> a;
2301 for (int x : {4, 1, 3, 2, 0, 2})
2302 a.append(x);
2303
2304 EXPECT_EQ(random_select(a, 0), 0);
2305 EXPECT_EQ(random_select(a, 5), 4);
2306}
2307
2308TEST(SortUtilsRandomSelect, random_select_out_of_range_and_empty)
2309{
2310 {
2311 DynArray<int> a;
2312 EXPECT_THROW(random_select(a, 0), std::out_of_range);
2313 }
2314
2315 {
2316 auto a = make_dynarray({4, 1, 3});
2317 EXPECT_THROW(random_select(a, 3), std::out_of_range);
2318 }
2319
2320 {
2321 Array<int> a;
2322 a.append(1);
2323 EXPECT_THROW(random_select(a, 1), std::out_of_range);
2324 }
2325
2326 {
2327 int b[] = {4, 1, 3};
2328 using Cmp = Aleph::less<int>;
2329 auto fn = static_cast<const int & (*)(int *, const long, const long, const Cmp &)>(
2330 &Aleph::random_select<int, Cmp>);
2331 EXPECT_THROW(fn(b, 3, 3, Cmp()), std::out_of_range);
2332 }
2333
2334 {
2335 Dnode<int> h;
2336 EXPECT_EQ(random_select<int>(h, 0), nullptr);
2337 EXPECT_EQ(random_select<int>(h, 1), nullptr);
2338 }
2339
2340 {
2342 EXPECT_EQ(random_select(l, 0), nullptr);
2343 EXPECT_EQ(random_select(l, 1), nullptr);
2344 }
2345
2346 {
2347 auto h = make_dnode_list({4, 1});
2348 EXPECT_THROW(random_select<int>(h, 2), std::out_of_range);
2349 delete_all_nodes(h);
2350 }
2351
2352 {
2353 auto l = make_dyndlist({4, 1});
2354 EXPECT_THROW(random_select(l, 2), std::out_of_range);
2355 }
2356}
2357
2358TEST(SortUtilsSearch, binary_search_insertion_point_container)
2359{
2360 auto a = make_dynarray({0, 2, 4, 6});
2361
2362 EXPECT_EQ(binary_search(a, 0), 0);
2363 EXPECT_EQ(binary_search(a, 6), 3);
2364
2365 // insertion points
2366 EXPECT_EQ(binary_search(a, 1), 1);
2367 EXPECT_EQ(binary_search(a, 5), 3);
2368 EXPECT_EQ(binary_search(a, 7), 4);
2369}
2370
2371TEST(SortUtilsSearch, binary_search_insertion_point_raw)
2372{
2373 int a[] = {0, 2, 4, 6};
2374 EXPECT_EQ(binary_search(a, 0, 0, 3), 0);
2375 EXPECT_EQ(binary_search(a, 6, 0, 3), 3);
2376 EXPECT_EQ(binary_search(a, 1, 0, 3), 1);
2377 EXPECT_EQ(binary_search(a, 5, 0, 3), 3);
2378 EXPECT_EQ(binary_search(a, 7, 0, 3), 4);
2379}
2380
2381TEST(SortUtilsSearch, binary_search_rec_insertion_point_raw)
2382{
2383 int a[] = {0, 2, 4, 6};
2384 EXPECT_EQ(binary_search_rec(a, 0, 0, 3), 0);
2385 EXPECT_EQ(binary_search_rec(a, 6, 0, 3), 3);
2386 EXPECT_EQ(binary_search_rec(a, 1, 0, 3), 1);
2387 EXPECT_EQ(binary_search_rec(a, 5, 0, 3), 3);
2388 EXPECT_EQ(binary_search_rec(a, 7, 0, 3), 4);
2389}
2390
2391TEST(SortUtilsSearch, random_select_dynarray_and_raw)
2392{
2393 auto a = make_dynarray({4, 1, 3, 2, 0, 2});
2394 EXPECT_EQ(random_select(a, 0), 0);
2395 EXPECT_EQ(random_select(a, 5), 4);
2396
2397 int b[] = {4, 1, 3, 2, 0, 2};
2398 using Cmp = Aleph::less<int>;
2399 auto fn = static_cast<const int & (*)(int *, const long, const long, const Cmp &)>(
2400 &Aleph::random_select<int, Cmp>);
2401 EXPECT_EQ(fn(b, 0, 6, Cmp()), 0);
2402 EXPECT_EQ(fn(b, 5, 6, Cmp()), 4);
2403}
2404
2405TEST(SortUtilsSearch, binary_search_ptr_container)
2406{
2407 auto a = make_dynarray({0, 2, 4, 6});
2408 DynArray<int *> idx;
2409 idx.reserve(a.size());
2410 for (size_t i = 0; i < a.size(); ++i)
2411 idx(i) = &a(i);
2412
2413 // already sorted pointers by value
2414 EXPECT_EQ(binary_search(idx, 0), 0);
2415 EXPECT_EQ(binary_search(idx, 6), 3);
2416 EXPECT_EQ(binary_search(idx, 1), 1);
2417 EXPECT_EQ(binary_search(idx, 7), 4);
2418}
2419
2420TEST(SortUtilsSearch, bsearch_dup_and_binindex_dup)
2421{
2422 auto a = make_dynarray({0, 1, 1, 1, 2, 3});
2423 auto ptrs = bsearch_dup(a, 1);
2424 ASSERT_EQ(ptrs.size(), 3u);
2425 for (auto p : ptrs)
2426 ASSERT_NE(p, nullptr);
2427
2428 auto idxs = binindex_dup(a, 1);
2429 ASSERT_EQ(idxs.size(), 3u);
2430 EXPECT_EQ(idxs.get_first(), 1);
2431 EXPECT_EQ(idxs.get_last(), 3);
2432}
2433
2434TEST(SortUtilsSearch, bsearch_dup_ptr_container_custom_compare_descending)
2435{
2436 auto a = make_dynarray({5, 4, 3, 3, 3, 2, 1, 1, 0});
2437 DynArray<int *> ptrs;
2438 ptrs.reserve(a.size());
2439 for (size_t i = 0; i < a.size(); ++i)
2440 ptrs(i) = &a(i);
2441
2442 auto dup = bsearch_dup(ptrs, 3, Aleph::greater<int>());
2443 ASSERT_EQ(dup.size(), 3u);
2444 for (auto p : dup)
2445 {
2446 ASSERT_NE(p, nullptr);
2447 EXPECT_EQ(*p, 3);
2448 }
2449}
2450
2451TEST(SortUtilsSearch, binindex_dup_ptr_container_custom_compare_descending)
2452{
2453 auto a = make_dynarray({5, 4, 3, 3, 3, 2, 1, 1, 0});
2454 DynArray<int *> ptrs;
2455 ptrs.reserve(a.size());
2456 for (size_t i = 0; i < a.size(); ++i)
2457 ptrs(i) = &a(i);
2458
2459 auto idxs = binindex_dup(ptrs, 3, Aleph::greater<int>());
2460 ASSERT_EQ(idxs.size(), 3u);
2461 EXPECT_EQ(idxs.get_first(), 2);
2462 EXPECT_EQ(idxs.get_last(), 4);
2463}
2464
2465TEST(SortUtilsSearch, bsearch_dup_ptr_container)
2466{
2467 auto a = make_dynarray({0, 1, 1, 1, 2, 3});
2468 DynArray<int *> ptrs;
2469 ptrs.reserve(a.size());
2470 for (size_t i = 0; i < a.size(); ++i)
2471 ptrs(i) = &a(i);
2472
2473 auto found = bsearch(ptrs, 1);
2474 ASSERT_NE(found, nullptr);
2475 EXPECT_EQ(*found, 1);
2476
2477 auto dup = bsearch_dup(ptrs, 1);
2478 ASSERT_EQ(dup.size(), 3u);
2479 for (auto p : dup)
2480 {
2481 ASSERT_NE(p, nullptr);
2482 EXPECT_EQ(*p, 1);
2483 }
2484}
2485
2486TEST(SortUtilsSearch, binindex_dup_ptr_container)
2487{
2488 auto a = make_dynarray({0, 1, 1, 1, 2, 3});
2489 DynArray<int *> ptrs;
2490 ptrs.reserve(a.size());
2491 for (size_t i = 0; i < a.size(); ++i)
2492 ptrs(i) = &a(i);
2493
2494 auto idxs = binindex_dup(ptrs, 1);
2495 ASSERT_EQ(idxs.size(), 3u);
2496 EXPECT_EQ(idxs.get_first(), 1);
2497 EXPECT_EQ(idxs.get_last(), 3);
2498}
2499
2500TEST(SortUtilsSearch, binary_search_ptr_container_custom_compare)
2501{
2502 auto a = make_dynarray({5, 4, 3, 2, 1, 0});
2503 DynArray<int *> ptrs;
2504 ptrs.reserve(a.size());
2505 for (size_t i = 0; i < a.size(); ++i)
2506 ptrs(i) = &a(i);
2507
2508 // The container is sorted in descending order, so we must use greater<int>
2509 EXPECT_EQ(binary_search(ptrs, 5, Aleph::greater<int>()), 0);
2510 EXPECT_EQ(binary_search(ptrs, 0, Aleph::greater<int>()), 5);
2511 EXPECT_EQ(binary_search(ptrs, 3, Aleph::greater<int>()), 2);
2512}
2513
2514TEST(SortUtilsSearch, binary_search_ptr_container_range_less)
2515{
2516 auto a = make_dynarray({0, 1, 2, 3, 4, 5});
2517 DynArray<int *> ptrs;
2518 ptrs.reserve(a.size());
2519 for (size_t i = 0; i < a.size(); ++i)
2520 ptrs(i) = &a(i);
2521
2522 // search only in [2..4] => values {2,3,4}
2523 EXPECT_EQ(binary_search(ptrs, 3, 2, 4), 3);
2524
2525 // insertion points within the restricted range
2526 EXPECT_EQ(binary_search(ptrs, 1, 2, 4), 2);
2527 EXPECT_EQ(binary_search(ptrs, 5, 2, 4), 5);
2528}
2529
2530TEST(SortUtilsSearch, binary_search_ptr_container_range_greater)
2531{
2532 auto a = make_dynarray({5, 4, 3, 2, 1, 0});
2533 DynArray<int *> ptrs;
2534 ptrs.reserve(a.size());
2535 for (size_t i = 0; i < a.size(); ++i)
2536 ptrs(i) = &a(i);
2537
2538 // search only in [1..3] => values {4,3,2} under greater<int>
2539 EXPECT_EQ(binary_search(ptrs, 3, 1, 3, Aleph::greater<int>()), 2);
2540
2541 // insertion points within the restricted range for descending order
2542 // 5 would be inserted before 4 => at l
2543 EXPECT_EQ(binary_search(ptrs, 5, 1, 3, Aleph::greater<int>()), 1);
2544 // 0 would be inserted after 2 => at r+1
2545 EXPECT_EQ(binary_search(ptrs, 0, 1, 3, Aleph::greater<int>()), 4);
2546}
2547
2548TEST(SortUtilsCountingSort, basic_sort_by_identity)
2549{
2552 sa[0] = 3; sa[1] = 0; sa[2] = 4; sa[3] = 1; sa[4] = 2;
2553
2554 counting_sort_indices(sa, tmp, 5, 0, 4,
2555 [](size_t idx) -> int { return static_cast<int>(idx); });
2556
2557 for (size_t i = 0; i < 5; ++i)
2558 EXPECT_EQ(sa[i], i);
2559}
2560
2569TEST(SortUtilsCountingSort, stability)
2570{
2571 // Two pairs with same key: (10,key=1) and (20,key=1)
2572 // Original order: indices 0(key=2), 1(key=1), 2(key=1), 3(key=0)
2575 sa[0] = 0; sa[1] = 1; sa[2] = 2; sa[3] = 3;
2576
2577 std::array<int, 4> keys = {2, 1, 1, 0};
2578 counting_sort_indices(sa, tmp, 4, 0, 2,
2579 [&](size_t idx) -> int { return keys[idx]; });
2580
2581 // Expected: 3(key=0), 1(key=1), 2(key=1), 0(key=2)
2582 EXPECT_EQ(sa[0], 3u);
2583 EXPECT_EQ(sa[1], 1u); // stable: 1 before 2
2584 EXPECT_EQ(sa[2], 2u);
2585 EXPECT_EQ(sa[3], 0u);
2586}
2587
2588TEST(SortUtilsCountingSort, negative_keys)
2589{
2592 sa[0] = 0; sa[1] = 1; sa[2] = 2; sa[3] = 3;
2593
2594 std::array<int, 4> keys = {0, -1, 2, -2};
2595 counting_sort_indices(sa, tmp, 4, -2, 2,
2596 [&](size_t idx) -> int { return keys[idx]; });
2597
2598 // Sorted by key: 3(-2), 1(-1), 0(0), 2(2)
2599 EXPECT_EQ(sa[0], 3u);
2600 EXPECT_EQ(sa[1], 1u);
2601 EXPECT_EQ(sa[2], 0u);
2602 EXPECT_EQ(sa[3], 2u);
2603}
2604
2605TEST(SortUtilsCountingSort, single_element)
2606{
2609 sa[0] = 42;
2610
2611 counting_sort_indices(sa, tmp, 1, 0, 0,
2612 [](size_t) -> int { return 0; });
2613 EXPECT_EQ(sa[0], 42u);
2614}
2615
2616TEST(SortUtilsCountingSort, empty)
2617{
2618 Array<size_t> sa;
2619 Array<size_t> tmp;
2620 counting_sort_indices(sa, tmp, 0, 0, 0,
2621 [](size_t) -> int { return 0; });
2622 EXPECT_TRUE(sa.is_empty());
2623}
2624
2625TEST(SortUtilsCountingSort, invalid_key_interval_throws)
2626{
2629 sa[0] = 0;
2630
2631 EXPECT_THROW(
2632 counting_sort_indices(sa, tmp, 1, 3, 2,
2633 [](size_t) -> int { return 0; }),
2634 std::domain_error);
2635}
2636
2637TEST(SortUtilsCountingSort, key_out_of_range_throws)
2638{
2641 sa[0] = 0;
2642 sa[1] = 1;
2643
2644 EXPECT_THROW(
2645 counting_sort_indices(sa, tmp, 2, 0, 1,
2646 [](size_t idx) -> int { return idx == 0 ? 0 : 2; }),
2647 std::out_of_range);
2648}
2649
2650TEST(SortUtilsCountingSort, insufficient_buffers_throw)
2651{
2654 sa[0] = 0;
2655
2656 EXPECT_THROW(
2657 counting_sort_indices(sa, tmp, 2, 0, 1,
2658 [](size_t idx) -> int { return static_cast<int>(idx); }),
2659 std::out_of_range);
2660}
2661
2662TEST(SortUtilsCountingSortGeneric, dynarray_signed_with_negatives)
2663{
2664 auto a = make_dynarray({5, -2, 3, -2, 0, 9, -10});
2665 counting_sort(a);
2666 EXPECT_EQ(a(0), -10);
2667 EXPECT_EQ(a(1), -2);
2668 EXPECT_EQ(a(2), -2);
2669 for (size_t i = 1; i < a.size(); ++i)
2670 ASSERT_LE(a(i - 1), a(i));
2671}
2672
2673TEST(SortUtilsCountingSortGeneric, array_unsigned_values)
2674{
2676 for (unsigned int x : {7u, 0u, 3u, 7u, 1u, 2u})
2677 a.append(x);
2678
2679 counting_sort(a);
2680 EXPECT_EQ(a(0), 0u);
2681 EXPECT_EQ(a(1), 1u);
2682 EXPECT_EQ(a(2), 2u);
2683 EXPECT_EQ(a(3), 3u);
2684 EXPECT_EQ(a(4), 7u);
2685 EXPECT_EQ(a(5), 7u);
2686}
2687
2688TEST(SortUtilsCountingSortGeneric, raw_pointer_and_nullptr_contract)
2689{
2690 int a[] = {4, 1, 3, 0, 2};
2691 counting_sort(a, sizeof(a) / sizeof(a[0]));
2692 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2693
2694 EXPECT_THROW((counting_sort<int>(nullptr, 1)), std::invalid_argument);
2695 EXPECT_NO_THROW((counting_sort<int>(nullptr, 0)));
2696}
2697
2698TEST(SortUtilsCountingSortGeneric, c_array_overload)
2699{
2700 int a[] = {5, 1, 4, 2, 3, 0};
2701 counting_sort(a);
2702 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2703}
2704
2705TEST(SortUtilsCountingSortGeneric, dynarray_support)
2706{
2707 auto a = make_dynarray({9, -1, 3, 0, -1, 2});
2708 counting_sort(a);
2709 for (size_t i = 1; i < a.size(); ++i)
2710 ASSERT_LE(a(i - 1), a(i));
2711 ASSERT_EQ(a.size(), 6u);
2712 EXPECT_EQ(a(0), -1);
2713 EXPECT_EQ(a(1), -1);
2714 EXPECT_EQ(a(5), 9);
2715}
2716
2717TEST(SortUtilsCountingSortGeneric, empty_and_singleton)
2718{
2719 DynArray<int> d;
2720 counting_sort(d);
2721 EXPECT_TRUE(d.is_empty());
2722
2723 Array<int> a;
2724 a.append(7);
2725 counting_sort(a);
2726 ASSERT_EQ(a.size(), 1u);
2727 EXPECT_EQ(a(0), 7);
2728}
2729
2730TEST(SortUtilsCountingSortGeneric, dynlist_support)
2731{
2732 DynList<int> l = make_dynlist({4, -1, 3, 0, -1, 2});
2734
2735 std::array<int, 6> expected = {-1, -1, 0, 2, 3, 4};
2736 size_t i = 0;
2737 for (DynList<int>::Iterator it(l); it.has_curr(); it.next(), ++i)
2738 EXPECT_EQ(it.get_curr(), expected[i]);
2739 EXPECT_EQ(i, expected.size());
2740}
2741
2742TEST(SortUtilsCountingSortGeneric, dynlist_preserves_nodes)
2743{
2744 DynList<int> l = make_dynlist({4, -1, 3, 0, -1, 2});
2745 const auto before = dynlist_node_addresses(l);
2747 const auto after = dynlist_node_addresses(l);
2748 expect_same_dynarray(before, after);
2749}
2750
2751TEST(SortUtilsCountingSortGeneric, dyndlist_support)
2752{
2753 DynDlist<int> l = make_dyndlist({7, 3, 7, 1, 0, -2});
2755
2756 std::array<int, 6> expected = {-2, 0, 1, 3, 7, 7};
2757 size_t i = 0;
2758 for (DynDlist<int>::Iterator it(l); it.has_curr(); it.next(), ++i)
2759 EXPECT_EQ(it.get_curr(), expected[i]);
2760 EXPECT_EQ(i, expected.size());
2761}
2762
2763TEST(SortUtilsCountingSortGeneric, dyndlist_preserves_nodes)
2764{
2765 DynDlist<int> l = make_dyndlist({7, 3, 7, 1, 0, -2});
2766 const auto before = dyndlist_node_addresses(l);
2768 const auto after = dyndlist_node_addresses(l);
2769 expect_same_dynarray(before, after);
2770}
2771
2772TEST(SortUtilsCountingSortGeneric, huge_range_throws)
2773{
2775 a.reserve(2);
2776 a(0) = 0ull;
2777 a(1) = std::numeric_limits<unsigned long long>::max();
2778 EXPECT_THROW(counting_sort(a), std::runtime_error);
2779}
2780
2781TEST(SortUtilsRadixSort, dynarray_signed_basic)
2782{
2783 auto a = make_dynarray({170, 45, 75, 90, 802, 24, 2, 66});
2784 radix_sort(a);
2785 for (size_t i = 1; i < a.size(); ++i)
2786 ASSERT_LE(a(i - 1), a(i));
2787}
2788
2789TEST(SortUtilsRadixSort, dynarray_with_negatives)
2790{
2791 auto a = make_dynarray({0, -1, 5, -10, 3, -1, 2});
2792 radix_sort(a);
2793 EXPECT_EQ(a(0), -10);
2794 EXPECT_EQ(a(1), -1);
2795 EXPECT_EQ(a(2), -1);
2796 for (size_t i = 1; i < a.size(); ++i)
2797 ASSERT_LE(a(i - 1), a(i));
2798}
2799
2800TEST(SortUtilsRadixSort, array_container)
2801{
2802 Array<int> a;
2803 for (int x : {9, 1, 8, 2, 7, 3, 6, 4, 5, 0})
2804 a.append(x);
2805
2806 radix_sort(a);
2807 for (size_t i = 1; i < a.size(); ++i)
2808 ASSERT_LE(a(i - 1), a(i));
2809}
2810
2811TEST(SortUtilsRadixSort, raw_pointer)
2812{
2813 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
2814 radix_sort(a, sizeof(a) / sizeof(a[0]));
2815 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2816}
2817
2818TEST(SortUtilsRadixSort, c_array_overload)
2819{
2820 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
2821 radix_sort(a);
2822 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2823}
2824
2825TEST(SortUtilsRadixSort, raw_pointer_nullptr_contract)
2826{
2827 EXPECT_THROW((radix_sort<int>(nullptr, 1)), std::invalid_argument);
2828 EXPECT_NO_THROW((radix_sort<int>(nullptr, 0)));
2829}
2830
2831TEST(SortUtilsRadixSort, dynlist_support)
2832{
2833 DynList<int> l = make_dynlist({3, -1, 2, -5, 0, 3});
2834 radix_sort(l);
2835
2836 std::array<int, 6> expected = {-5, -1, 0, 2, 3, 3};
2837 size_t i = 0;
2838 for (DynList<int>::Iterator it(l); it.has_curr(); it.next(), ++i)
2839 EXPECT_EQ(it.get_curr(), expected[i]);
2840 EXPECT_EQ(i, expected.size());
2841}
2842
2843TEST(SortUtilsRadixSort, dynlist_preserves_nodes)
2844{
2845 DynList<int> l = make_dynlist({3, -1, 2, -5, 0, 3});
2846 const auto before = dynlist_node_addresses(l);
2847 radix_sort(l);
2848 const auto after = dynlist_node_addresses(l);
2849 expect_same_dynarray(before, after);
2850}
2851
2852TEST(SortUtilsRadixSort, dyndlist_support)
2853{
2854 DynDlist<int> l = make_dyndlist({10, -2, 7, 0, -2, 1});
2855 radix_sort(l);
2856
2857 std::array<int, 6> expected = {-2, -2, 0, 1, 7, 10};
2858 size_t i = 0;
2859 for (DynDlist<int>::Iterator it(l); it.has_curr(); it.next(), ++i)
2860 EXPECT_EQ(it.get_curr(), expected[i]);
2861 EXPECT_EQ(i, expected.size());
2862}
2863
2864TEST(SortUtilsRadixSort, dyndlist_preserves_nodes)
2865{
2866 DynDlist<int> l = make_dyndlist({10, -2, 7, 0, -2, 1});
2867 const auto before = dyndlist_node_addresses(l);
2868 radix_sort(l);
2869 const auto after = dyndlist_node_addresses(l);
2870 expect_same_dynarray(before, after);
2871}
2872
2873TEST(SortUtilsRadixSort, signed_extremes)
2874{
2875 DynArray<int> a;
2876 a.reserve(6);
2877 a(0) = std::numeric_limits<int>::max();
2878 a(1) = 0;
2879 a(2) = std::numeric_limits<int>::min();
2880 a(3) = -1;
2881 a(4) = std::numeric_limits<int>::max();
2882 a(5) = std::numeric_limits<int>::min();
2883
2884 radix_sort(a);
2885
2886 EXPECT_EQ(a(0), std::numeric_limits<int>::min());
2887 EXPECT_EQ(a(1), std::numeric_limits<int>::min());
2888 EXPECT_EQ(a(4), std::numeric_limits<int>::max());
2889 EXPECT_EQ(a(5), std::numeric_limits<int>::max());
2890 for (size_t i = 1; i < a.size(); ++i)
2891 ASSERT_LE(a(i - 1), a(i));
2892}
2893
2894TEST(SortUtilsRadixSort, unsigned_values)
2895{
2897 for (unsigned int x : {std::numeric_limits<unsigned int>::max(),
2898 0u, 10u, 1u, 1024u, 10u})
2899 a.append(x);
2900
2901 radix_sort(a);
2902
2903 EXPECT_EQ(a(0), 0u);
2904 EXPECT_EQ(a(1), 1u);
2905 EXPECT_EQ(a(2), 10u);
2906 EXPECT_EQ(a(3), 10u);
2907 EXPECT_EQ(a(a.size() - 1), std::numeric_limits<unsigned int>::max());
2908 for (size_t i = 1; i < a.size(); ++i)
2909 ASSERT_LE(a(i - 1), a(i));
2910}
2911
2912TEST(SortUtilsRadixSort, empty_and_singleton)
2913{
2914 DynArray<int> d;
2915 radix_sort(d);
2916 EXPECT_EQ(d.size(), 0u);
2917
2918 Array<int> a;
2919 a.append(7);
2920 radix_sort(a);
2921 ASSERT_EQ(a.size(), 1u);
2922 EXPECT_EQ(a(0), 7);
2923}
2924
2925TEST(SortUtilsRandomSelect, duplicates_three_way_partition)
2926{
2927 DynArray<int> v = make_dynarray({9, 2, 4, 7, 3, 7, 10, 2, 7, 1, 8, 7, 7, 7, 7});
2928 std::vector<int> expected = {9, 2, 4, 7, 3, 7, 10, 2, 7, 1, 8, 7, 7, 7, 7};
2929 std::sort(expected.begin(), expected.end());
2930
2931 for (size_t i = 0; i < v.size(); ++i)
2932 {
2933 DynArray<int> copy = v;
2934 int res = Aleph::random_select(&copy(0), static_cast<long>(i), static_cast<long>(copy.size()), std::less<int>());
2935 EXPECT_EQ(res, expected[i]) << "Mismatch at index " << i;
2936 }
2937}
2938
2939TEST(SortUtilsRandomSelect, identical_elements)
2940{
2941 DynArray<int> v;
2942 for (int i = 0; i < 100; ++i)
2943 v.append(42);
2944
2945 for (size_t i = 0; i < v.size(); i += 10)
2946 {
2947 DynArray<int> copy = v;
2948 int res = Aleph::random_select(&copy(0), static_cast<long>(i), static_cast<long>(copy.size()), std::less<int>());
2949 EXPECT_EQ(res, 42) << "Mismatch at index " << i;
2950 }
2951}
2952
2953TEST(SortUtilsRandomSelect, sorted_and_reverse_sorted)
2954{
2955 DynArray<int> v;
2956 for (int i = 0; i < 50; ++i)
2957 v.append(i);
2958
2959 DynArray<int> rev;
2960 for (int i = 49; i >= 0; --i)
2961 rev.append(i);
2962
2963 for (size_t i = 0; i < v.size(); i += 5)
2964 {
2965 DynArray<int> copy_v = v;
2966 DynArray<int> copy_rev = rev;
2967
2968 EXPECT_EQ(Aleph::random_select(&copy_v(0), static_cast<long>(i), static_cast<long>(copy_v.size()), std::less<int>()), static_cast<int>(i));
2969 EXPECT_EQ(Aleph::random_select(&copy_rev(0), static_cast<long>(i), static_cast<long>(copy_rev.size()), std::less<int>()), static_cast<int>(i));
2970 }
2971}
2972
2973TEST(SortUtilsRandomSelect, RandomizedSeededProperty)
2974{
2975 std::mt19937 gen(42);
2976 for (int iter = 0; iter < 100; ++iter)
2977 {
2978 const size_t N = std::uniform_int_distribution<size_t>(1, 200)(gen);
2979 DynArray<int> a;
2980 std::vector<int> expected;
2981 for (size_t i = 0; i < N; ++i)
2982 {
2983 int val = std::uniform_int_distribution<int>(-1000, 1000)(gen);
2984 a.append(val);
2985 expected.push_back(val);
2986 }
2987 std::sort(expected.begin(), expected.end());
2988
2989 const long k = std::uniform_int_distribution<long>(0, static_cast<long>(N) - 1)(gen);
2990 DynArray<int> copy = a;
2991 int res = Aleph::random_select(&copy(0), k, static_cast<long>(N), std::less<int>());
2992 EXPECT_EQ(res, expected[k]) << "Mismatch at iter " << iter << " rank " << k << " N " << N;
2993 }
2994}
2995
2996// ================================================================
2997// Bucket Sort Tests
2998// ================================================================
2999
3000TEST(BucketSort, float_uniform)
3001{
3002 constexpr size_t N = 500;
3004 a.reserve(N);
3005 std::mt19937 gen(42);
3006 std::uniform_real_distribution<float> dist(0.0f, 1.0f);
3007 for (size_t i = 0; i < N; ++i)
3008 a(i) = dist(gen);
3009
3010 bucket_sort(a);
3011 for (size_t i = 1; i < N; ++i)
3012 ASSERT_LE(a(i - 1), a(i));
3013}
3014
3015TEST(BucketSort, float_with_negatives)
3016{
3017 constexpr size_t N = 300;
3019 a.reserve(N);
3020 std::mt19937 gen(123);
3021 std::uniform_real_distribution<float> dist(-100.0f, 100.0f);
3022 for (size_t i = 0; i < N; ++i)
3023 a(i) = dist(gen);
3024
3025 bucket_sort(a);
3026 for (size_t i = 1; i < N; ++i)
3027 ASSERT_LE(a(i - 1), a(i));
3028}
3029
3030TEST(BucketSort, double_support)
3031{
3032 constexpr size_t N = 200;
3034 a.reserve(N);
3035 std::mt19937 gen(77);
3036 std::uniform_real_distribution<double> dist(-50.0, 50.0);
3037 for (size_t i = 0; i < N; ++i)
3038 a(i) = dist(gen);
3039
3040 bucket_sort(a);
3041 for (size_t i = 1; i < N; ++i)
3042 ASSERT_LE(a(i - 1), a(i));
3043}
3044
3045TEST(BucketSort, descending_order)
3046{
3047 constexpr size_t N = 100;
3049 a.reserve(N);
3050 std::mt19937 gen(99);
3051 std::uniform_real_distribution<double> dist(-10.0, 10.0);
3052 for (size_t i = 0; i < N; ++i)
3053 a(i) = dist(gen);
3054
3056 for (size_t i = 1; i < N; ++i)
3057 ASSERT_GE(a(i - 1), a(i)) << "Failed at index " << i << " values: " << a(i-1) << ", " << a(i);
3058}
3059
3060TEST(BucketSort, custom_bucket_key)
3061{
3062 int a[] = {95, 23, 67, 12, 45, 78, 34, 56, 89, 1};
3063 const size_t n = sizeof(a) / sizeof(a[0]);
3064 const size_t num_buckets = 10;
3065
3066 auto key = [](const int & val) -> size_t
3067 {
3068 return static_cast<size_t>(val / 10);
3069 };
3070
3071 bucket_sort(a, n, num_buckets, key);
3072 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3073}
3074
3075TEST(BucketSort, custom_bucket_key_move_only_pointer)
3076{
3077 struct MoveOnlyInt
3078 {
3079 int value = 0;
3080
3081 MoveOnlyInt() = default;
3082 explicit MoveOnlyInt(const int v) : value(v) {}
3083 MoveOnlyInt(const MoveOnlyInt &) = delete;
3084 MoveOnlyInt & operator = (const MoveOnlyInt &) = delete;
3085 MoveOnlyInt(MoveOnlyInt &&) noexcept = default;
3086 MoveOnlyInt & operator = (MoveOnlyInt &&) noexcept = default;
3087 };
3088
3089 static_assert(not std::is_copy_constructible_v<MoveOnlyInt>);
3090 static_assert(not std::is_copy_assignable_v<MoveOnlyInt>);
3091
3092 MoveOnlyInt a[] = {
3093 MoveOnlyInt(7), MoveOnlyInt(1), MoveOnlyInt(4), MoveOnlyInt(0),
3094 MoveOnlyInt(6), MoveOnlyInt(2), MoveOnlyInt(5), MoveOnlyInt(3)
3095 };
3096 const size_t n = sizeof(a) / sizeof(a[0]);
3097 const size_t num_buckets = 4;
3098 auto key = [](const MoveOnlyInt & x) -> size_t
3099 {
3100 return static_cast<size_t>(x.value / 2);
3101 };
3102 auto cmp = [](const MoveOnlyInt & lhs, const MoveOnlyInt & rhs)
3103 {
3104 return lhs.value < rhs.value;
3105 };
3106
3107 bucket_sort(a, n, num_buckets, key, cmp);
3108
3109 for (size_t i = 1; i < n; ++i)
3110 ASSERT_LE(a[i - 1].value, a[i].value);
3111}
3112
3113TEST(BucketSort, dynarray_support)
3114{
3115 constexpr size_t N = 100;
3117 a.reserve(N);
3118 std::mt19937 gen(55);
3119 std::uniform_real_distribution<double> dist(0.0, 1.0);
3120 for (size_t i = 0; i < N; ++i)
3121 a(i) = dist(gen);
3122
3123 bucket_sort(a);
3124 for (size_t i = 1; i < N; ++i)
3125 ASSERT_LE(a(i - 1), a(i));
3126}
3127
3128TEST(BucketSort, array_support)
3129{
3130 Array<double> a;
3131 std::mt19937 gen(99);
3132 std::uniform_real_distribution<double> dist(-10.0, 10.0);
3133 for (size_t i = 0; i < 50; ++i)
3134 a.append(dist(gen));
3135
3136 bucket_sort(a);
3137 for (size_t i = 1; i < a.size(); ++i)
3138 ASSERT_LE(a(i - 1), a(i));
3139}
3140
3141TEST(BucketSort, c_array_overload)
3142{
3143 double a[] = {3.5, 1.2, 4.8, 0.3, 2.7, 1.9, 4.1, 0.1};
3144 bucket_sort(a);
3145 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3146}
3147
3148TEST(BucketSort, dynlist_support)
3149{
3151 l.append(3.5);
3152 l.append(1.2);
3153 l.append(4.8);
3154 l.append(0.3);
3155 l.append(2.7);
3156
3157 bucket_sort(l);
3158
3159 double prev = -std::numeric_limits<double>::infinity();
3160 for (DynList<double>::Iterator it(l); it.has_curr(); it.next())
3161 {
3162 EXPECT_GE(it.get_curr(), prev);
3163 prev = it.get_curr();
3164 }
3165}
3166
3167TEST(BucketSort, empty_and_singleton)
3168{
3170 bucket_sort(d);
3171 EXPECT_EQ(d.size(), 0u);
3172
3174 s.reserve(1);
3175 s(0) = 42.0f;
3176 bucket_sort(s);
3177 ASSERT_EQ(s.size(), 1u);
3178 EXPECT_FLOAT_EQ(s(0), 42.0f);
3179}
3180
3181TEST(BucketSort, all_equal)
3182{
3183 constexpr size_t N = 50;
3185 a.reserve(N);
3186 for (size_t i = 0; i < N; ++i)
3187 a(i) = 7.7f;
3188
3189 bucket_sort(a);
3190 for (size_t i = 0; i < N; ++i)
3191 EXPECT_FLOAT_EQ(a(i), 7.7f);
3192}
3193
3194TEST(BucketSort, reverse_sorted_input)
3195{
3196 constexpr size_t N = 100;
3198 a.reserve(N);
3199 for (size_t i = 0; i < N; ++i)
3200 a(i) = static_cast<double>(N - i);
3201
3202 bucket_sort(a);
3203 for (size_t i = 1; i < N; ++i)
3204 ASSERT_LE(a(i - 1), a(i));
3205}
3206
3207TEST(BucketSort, null_pointer_contract)
3208{
3209 EXPECT_THROW((bucket_sort<float>(nullptr, 1)), std::invalid_argument);
3210 EXPECT_NO_THROW((bucket_sort<float>(nullptr, 0)));
3211}
3212
3213TEST(BucketSort, stability)
3214{
3215 // Records with same bucket should preserve relative order
3216 struct Record
3217 {
3218 int group;
3219 int seq;
3220 };
3221
3222 Record data[] = {{0, 0}, {2, 1}, {0, 2}, {1, 3}, {2, 4}, {1, 5}};
3223 const size_t n = sizeof(data) / sizeof(data[0]);
3224 const size_t num_buckets = 3;
3225
3226 auto key = [](const Record & r) -> size_t { return r.group; };
3227 auto cmp = [](const Record & a, const Record & b) { return a.group < b.group; };
3228
3229 bucket_sort(data, n, num_buckets, key, cmp);
3230
3231 // Verify sorted by group
3232 for (size_t i = 1; i < n; ++i)
3233 ASSERT_LE(data[i - 1].group, data[i].group);
3234
3235 // Verify stability: within same group, original order preserved
3236 // Group 0: seq 0, 2
3237 EXPECT_EQ(data[0].seq, 0);
3238 EXPECT_EQ(data[1].seq, 2);
3239 // Group 1: seq 3, 5
3240 EXPECT_EQ(data[2].seq, 3);
3241 EXPECT_EQ(data[3].seq, 5);
3242 // Group 2: seq 1, 4
3243 EXPECT_EQ(data[4].seq, 1);
3244 EXPECT_EQ(data[5].seq, 4);
3245}
3246
3247
3248TEST(BucketSort, zero_buckets)
3249{
3250 int a[] = {3, 1, 2};
3251 const size_t n = 3;
3252 const size_t num_buckets = 0;
3253 auto key = [](const int &) -> size_t { return 0; };
3254
3255 // Zero buckets with n >= 2 must throw domain_error
3256 EXPECT_THROW(bucket_sort(a, n, num_buckets, key), std::domain_error);
3257}
3258
3259// ================================================================
3260// Timsort Tests
3261// ================================================================
3262
3263TEST(Timsort, already_sorted)
3264{
3265 constexpr size_t N = 200;
3266 DynArray<int> a;
3267 a.reserve(N);
3268 for (size_t i = 0; i < N; ++i)
3269 a(i) = static_cast<int>(i);
3270
3271 timsort(a);
3272 for (size_t i = 1; i < N; ++i)
3273 ASSERT_LE(a(i - 1), a(i));
3274}
3275
3276TEST(Timsort, reverse_sorted)
3277{
3278 constexpr size_t N = 200;
3279 DynArray<int> a;
3280 a.reserve(N);
3281 for (size_t i = 0; i < N; ++i)
3282 a(i) = static_cast<int>(N - i);
3283
3284 timsort(a);
3285 for (size_t i = 1; i < N; ++i)
3286 ASSERT_LE(a(i - 1), a(i));
3287}
3288
3289TEST(Timsort, random_small)
3290{
3291 int a[] = {5, 3, 8, 1, 9, 2, 7, 4, 6, 0};
3292 timsort(static_cast<int*>(a), size_t{10});
3293 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3294}
3295
3296TEST(Timsort, random_large)
3297{
3298 constexpr size_t N = 10000;
3299 DynArray<int> a;
3300 a.reserve(N);
3301 std::mt19937 gen(42);
3302 std::uniform_int_distribution<int> dist(-1000000, 1000000);
3303 for (size_t i = 0; i < N; ++i)
3304 a(i) = dist(gen);
3305
3306 timsort(a);
3307 for (size_t i = 1; i < N; ++i)
3308 ASSERT_LE(a(i - 1), a(i));
3309}
3310
3311TEST(Timsort, perf_large)
3312{
3313 if (not std::getenv("ENABLE_PERF_TESTS"))
3314 GTEST_SKIP() << "Skipping perf test (set ENABLE_PERF_TESTS to enable)";
3315
3316 constexpr size_t N = 100000;
3317 DynArray<int> a;
3318 a.reserve(N);
3319 std::mt19937 gen(42);
3320 std::uniform_int_distribution<int> dist(-1000000, 1000000);
3321 for (size_t i = 0; i < N; ++i)
3322 a(i) = dist(gen);
3323
3324 auto start = std::chrono::steady_clock::now();
3325 timsort(a);
3326 auto end = std::chrono::steady_clock::now();
3327
3328 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
3329
3330 long max_ms = 500;
3331 if (const char * env_ms = std::getenv("TIMSORT_MAX_MS"))
3332 max_ms = std::atol(env_ms);
3333
3334 EXPECT_LE(duration, max_ms) << "Timsort performance regression detected";
3335
3336 for (size_t i = 1; i < N; ++i)
3337 ASSERT_LE(a(i - 1), a(i));
3338}
3339
3340TEST(Timsort, all_equal)
3341{
3342 constexpr size_t N = 100;
3343 DynArray<int> a;
3344 a.reserve(N);
3345 for (size_t i = 0; i < N; ++i)
3346 a(i) = 42;
3347
3348 timsort(a);
3349 for (size_t i = 0; i < N; ++i)
3350 EXPECT_EQ(a(i), 42);
3351}
3352
3353TEST(Timsort, two_sorted_halves)
3354{
3355 constexpr size_t N = 200;
3356 DynArray<int> a;
3357 a.reserve(N);
3358 // First half: 0, 2, 4, ... 198
3359 for (size_t i = 0; i < N / 2; ++i)
3360 a(i) = static_cast<int>(i * 2);
3361 // Second half: 1, 3, 5, ... 199
3362 for (size_t i = N / 2; i < N; ++i)
3363 a(i) = static_cast<int>((i - N / 2) * 2 + 1);
3364
3365 timsort(a);
3366 for (size_t i = 1; i < N; ++i)
3367 ASSERT_LE(a(i - 1), a(i));
3368}
3369
3370TEST(Timsort, custom_comparator)
3371{
3372 constexpr size_t N = 50;
3373 DynArray<int> a;
3374 a.reserve(N);
3375 std::mt19937 gen(99);
3376 for (size_t i = 0; i < N; ++i)
3377 a(i) = static_cast<int>(gen() % 1000);
3378
3380 for (size_t i = 1; i < N; ++i)
3381 ASSERT_GE(a(i - 1), a(i));
3382}
3383
3384TEST(Timsort, dynarray_support)
3385{
3386 auto a = make_dynarray({9, 1, 8, 2, 7, 3, 6, 4, 5, 0});
3387 timsort(a);
3388 for (size_t i = 1; i < a.size(); ++i)
3389 ASSERT_LE(a(i - 1), a(i));
3390}
3391
3392TEST(Timsort, array_support)
3393{
3394 Array<int> a;
3395 for (int x : {9, 1, 8, 2, 7, 3, 6, 4, 5, 0})
3396 a.append(x);
3397
3398 timsort(a);
3399 for (size_t i = 1; i < a.size(); ++i)
3400 ASSERT_LE(a(i - 1), a(i));
3401}
3402
3403TEST(Timsort, c_array_overload)
3404{
3405 int a[] = {5, 3, 8, 1, 9, 2, 7, 4, 6, 0};
3406 timsort(a);
3407 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3408}
3409
3410TEST(Timsort, dynlist_support)
3411{
3412 DynList<int> l = make_dynlist({5, 3, 8, 1, 9, 2, 7, 4, 6, 0});
3413 timsort(l);
3414
3415 int prev = std::numeric_limits<int>::min();
3416 for (DynList<int>::Iterator it(l); it.has_curr(); it.next())
3417 {
3418 EXPECT_GE(it.get_curr(), prev);
3419 prev = it.get_curr();
3420 }
3421}
3422
3423TEST(Timsort, empty_and_singleton)
3424{
3425 DynArray<int> d;
3426 timsort(d);
3427 EXPECT_EQ(d.size(), 0u);
3428
3429 Array<int> a;
3430 a.append(7);
3431 timsort(a);
3432 ASSERT_EQ(a.size(), 1u);
3433 EXPECT_EQ(a(0), 7);
3434}
3435
3436TEST(Timsort, null_pointer_contract)
3437{
3438 EXPECT_THROW((timsort<int>(nullptr, 1)), std::invalid_argument);
3439 EXPECT_NO_THROW((timsort<int>(nullptr, 0)));
3440}
3441
3442TEST(Timsort, stability)
3443{
3444 struct Record
3445 {
3446 int key;
3447 int seq; // original order
3448 bool operator<(const Record & rhs) const { return key < rhs.key; }
3449 };
3450
3451 Record data[] = {
3452 {3, 0}, {1, 1}, {4, 2}, {1, 3}, {5, 4},
3453 {9, 5}, {2, 6}, {6, 7}, {5, 8}, {3, 9}
3454 };
3455 const size_t n = sizeof(data) / sizeof(data[0]);
3456
3457 auto cmp = [](const Record & a, const Record & b) { return a.key < b.key; };
3458 timsort(data, n, cmp);
3459
3460 // Verify sorted by key
3461 for (size_t i = 1; i < n; ++i)
3462 ASSERT_LE(data[i - 1].key, data[i].key);
3463
3464 // Verify stability: equal keys preserve original seq order
3465 for (size_t i = 1; i < n; ++i)
3466 if (data[i - 1].key == data[i].key)
3467 {
3468 EXPECT_LT(data[i - 1].seq, data[i].seq)
3469 << "Stability violated at index " << i;
3470 }
3471}
3472
3473TEST(Timsort, string_sort)
3474{
3476 a.append("banana");
3477 a.append("apple");
3478 a.append("cherry");
3479 a.append("date");
3480 a.append("apricot");
3481
3483
3484 EXPECT_EQ(a(0), "apple");
3485 EXPECT_EQ(a(1), "apricot");
3486 EXPECT_EQ(a(2), "banana");
3487 EXPECT_EQ(a(3), "cherry");
3488 EXPECT_EQ(a(4), "date");
3489}
3490
3491TEST(Timsort, nearly_sorted)
3492{
3493 constexpr size_t N = 500;
3494 DynArray<int> a;
3495 a.reserve(N);
3496 for (size_t i = 0; i < N; ++i)
3497 a(i) = static_cast<int>(i);
3498
3499 // Introduce a few inversions
3500 std::mt19937 gen(12);
3501 for (int k = 0; k < 10; ++k)
3502 {
3503 size_t i = gen() % N;
3504 size_t j = gen() % N;
3505 std::swap(a(i), a(j));
3506 }
3507
3508 timsort(a);
3509 for (size_t i = 1; i < N; ++i)
3510 ASSERT_LE(a(i - 1), a(i));
3511}
3512
3513TEST(Timsort, range_overload)
3514{
3515 int a[] = {9, 5, 3, 8, 1, 7, 2, 6, 4, 0};
3516 // Sort only the subrange [2, 7] (inclusive)
3517 timsort(a, 2L, 7L);
3518
3519 // a[2..7] should be sorted
3520 for (int i = 3; i <= 7; ++i)
3521 ASSERT_LE(a[i - 1], a[i]);
3522
3523 // Elements outside the range should be unchanged
3524 EXPECT_EQ(a[0], 9);
3525 EXPECT_EQ(a[1], 5);
3526 EXPECT_EQ(a[8], 4);
3527 EXPECT_EQ(a[9], 0);
3528}
3529
3530TEST(Timsort, compute_minrun)
3531{
3533
3534 // n < 64: minrun == n
3535 EXPECT_EQ(compute_minrun(1), 1u);
3536 EXPECT_EQ(compute_minrun(32), 32u);
3537 EXPECT_EQ(compute_minrun(63), 63u);
3538
3539 // n == 64: minrun == 32
3540 EXPECT_EQ(compute_minrun(64), 32u);
3541
3542 // minrun should always be in [32, 64] for n >= 64
3543 for (size_t n = 64; n < 10000; ++n)
3544 {
3545 const size_t mr = compute_minrun(n);
3546 EXPECT_GE(mr, 32u) << "n=" << n;
3547 EXPECT_LE(mr, 64u) << "n=" << n;
3548 }
3549}
3550
3551} // namespace
static DynArray< int > make_dynarray(std::initializer_list< int > vals)
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
static bool is_min_heap(const std::vector< int > &v)
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
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
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
Helper class to compare nodes of a linked list.
Iterator on a list of Dnode objects.
Definition tpl_dnode.H:294
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
size_t size() const noexcept
Return the current dimension of array.
T & append()
Allocate a new entry to the end of array.
bool is_empty() const noexcept
Return true if the array is empty.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Iterator dynamic list.
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
T & append(const T &item)
Append a copied item at the end of the list.
Iterator on the items of list.
Definition htlist.H:1614
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & append(const T &item)
Definition htlist.H:1362
T & get_last()
Return the last item of the list.
Definition htlist.H:1529
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Fixed length stack.
bool has_curr() const noexcept
Definition htlist.H:969
Single linked list of nodes.
Definition htlist.H:420
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Comparator wrapper that inverts the comparison order.
Link of a single linked list non-circular and without header node.
Definition htlist.H:95
constexpr bool is_empty() const noexcept
Return true if this is empty.
Definition htlist.H:102
Slinknc * remove_next() noexcept
Definition htlist.H:159
void insert(Slinknc *p) noexcept
insert(p) inserts the node pointed by p after this.
Definition htlist.H:146
Minimal std::expected-style result type for C++20.
#define TEST(name)
static mt19937 rng
#define N
Definition fib.C:294
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
static mpfr_t y
Definition mpfr_mul_d.c:3
constexpr size_t compute_minrun(size_t n) noexcept
Compute the minimum run length for timsort.
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.
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).
std::pair< bool, size_t > search_inversion(const Container< T > &cont, const Compare &cmp=Compare())
Find the first inversion in a container.
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 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.
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< bool, size_t > test_sorted(const Container< T > &cont, const Compare &cmp=Compare())
Test if a container is sorted, returning the inversion position.
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.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
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.
DynArray< T > sort(const DynArray< T > &a, Cmp &&cmp=Cmp())
Returns a sorted copy of a DynArray.
Definition ahSort.H:234
Array< size_t > build_index(const C &a, const Compare &cmp=Compare())
Build an index array for indirect sorting.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
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.
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.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
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).
constexpr void heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Sort an array using the heapsort algorithm.
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.
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.
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.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
DynList< int > l1
DynList< int > l2
int keys[]
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Doubly linked list node with typed data.
Lazy and scalable dynamic array implementation.
Dynamic doubly linked list implementation.
Alias for htlist.H (DynList implementation).
Comprehensive sorting algorithms and search utilities for Aleph-w.
DynList< int > l