37#include <gtest/gtest.h>
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>);
84 for (
const int x : xs)
89template <
class Compare>
90std::vector<size_t> stable_index_reference(
const std::vector<int> &values,
93 std::vector<size_t> ref(values.size());
94 for (
size_t i = 0; i < ref.size(); ++i)
97 std::stable_sort(ref.begin(), ref.end(),
98 [&values, &
cmp](
const size_t i,
const size_t j)
100 return cmp(values[i], values[j]);
106template <
class Index>
107void expect_index_matches_reference(
const Index &idx,
108 const std::vector<size_t> &ref)
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;
115template <
class Compare>
116void expect_stable_build_index_matches_reference_exhaustively(
const Compare &
cmp)
118 constexpr size_t max_n = 7;
119 constexpr size_t alphabet = 3;
121 for (
size_t n = 0; n <= max_n; ++n)
124 for (
size_t i = 0; i < n; ++i)
129 std::vector<int> values(n);
131 for (
size_t i = 0; i < n; ++i)
133 values[i] =
static_cast<int>(x % alphabet);
138 const auto ref = stable_index_reference(values,
cmp);
139 expect_index_matches_reference(idx, ref);
144static DynList<int> make_dynlist(std::initializer_list<int> xs)
152static DynDlist<int> make_dyndlist(std::initializer_list<int> xs)
160static Dnode<int> make_dnode_list(std::initializer_list<int> xs)
164 h.append(new
Dnode<int>(x));
177 while (not
h.is_empty())
210 for (
size_t i = 0; i < a.
size(); ++i)
211 EXPECT_EQ(a(i), b(i));
228 ret(i++) =
reinterpret_cast<uintptr_t
>(it.get_curr());
250 ret(i++) =
reinterpret_cast<uintptr_t
>(it.get_curr());
255TEST(SortUtilsSortedness, allows_equal)
263TEST(SortUtilsSortedness, detects_inversion)
268 EXPECT_FALSE(inv.first);
269 EXPECT_EQ(inv.second, 2u);
272TEST(SortUtilsSortedness, inversely_sorted)
279TEST(SortUtilsArraySorts, selection_sort_empty_and_single)
287TEST(SortUtilsArraySorts, selection_sort_basic)
289 int a[] = {3, 1, 2, 1, 0};
291 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
294TEST(SortUtilsArraySorts, insertion_sort_subrange)
308TEST(SortUtilsArraySorts, selection_sort_dynarray)
312 for (
size_t i = 1; i < a.size(); ++i)
313 ASSERT_LE(a(i - 1), a(i));
316TEST(SortUtilsArraySorts, selection_sort_dynarray_custom_compare_desc)
320 for (
size_t i = 1; i < a.size(); ++i)
321 ASSERT_GE(a(i - 1), a(i));
324TEST(SortUtilsArraySorts, bubble_sort_dynarray)
328 for (
size_t i = 1; i < a.size(); ++i)
329 ASSERT_LE(a(i - 1), a(i));
332TEST(SortUtilsArraySorts, bubble_sort_dynarray_already_sorted_with_duplicates)
336 for (
size_t i = 1; i < a.size(); ++i)
337 ASSERT_LE(a(i - 1), a(i));
347 for (
size_t child = 2; child <= n; ++child)
349 size_t parent = child / 2;
350 if (a(parent - 1) > a(child - 1))
356TEST(SortUtilsHelpers, select_pivot_op_dynarray_median_of_three)
360 long p = select_pivot_op<int>(a, 0, 6);
361 EXPECT_TRUE(p == 3 || p == 6);
365 EXPECT_EQ(select_pivot_op<int>(b, 0, 6), 0);
369 EXPECT_EQ(select_pivot_op<int>(c, 0, 6), 3);
372TEST(SortUtilsHelpers, select_pivot_op_array_small_range_returns_r)
375 for (
int x : {5, 4, 3, 2, 1, 0})
379 EXPECT_EQ(select_pivot_op<int>(a, 0, 5), 5);
382TEST(SortUtilsHelpers, partition_op_dynarray_invariants)
385 std::vector<int> before;
387 for (
size_t i = 0; i < a.
size(); ++i)
388 before.push_back(a(i));
390 long p = partition_op<int>(a, 0,
static_cast<long>(a.
size() - 1));
392 ASSERT_LT(
static_cast<size_t>(p), a.
size());
394 const int pivot = a(p);
395 for (
long i = 0; i < p; ++i)
397 for (
long i = p + 1; i < static_cast<long>(a.
size()); ++i)
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);
409TEST(SortUtilsHelpers, partition_op_array_invariants)
412 for (
int x : {4, 1, 3, 2, 0, 2})
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));
420 long p = partition_op<int>(a, 0,
static_cast<long>(a.
size() - 1));
422 ASSERT_LT(
static_cast<size_t>(p), a.
size());
424 const int pivot = a(p);
425 for (
long i = 0; i < p; ++i)
427 for (
long i = p + 1; i < static_cast<long>(a.
size()); ++i)
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);
439TEST(SortUtilsHelpers, __random_select_dynarray_and_array)
443 auto expected = std::vector<int>{4, 1, 3, 2, 0, 2};
452 for (
int x : {4, 1, 3, 2, 0, 2})
454 auto expected = std::vector<int>{4, 1, 3, 2, 0, 2};
462TEST(SortUtilsHelpers, back_index_and_negate_compare)
467 EXPECT_TRUE(nc(2, 1));
468 EXPECT_FALSE(nc(1, 2));
471TEST(SortUtilsHelpers, select_pivot_and_partition_raw)
473 int a[] = {4, 1, 3, 2, 0, 2};
475 int p = select_pivot<int, Aleph::less<int>>(a, 0, 5,
cmp);
479 int q = partition<int, Aleph::less<int>>(a, 0, 5,
cmp);
484TEST(SortUtilsHelpers, merge_raw_partitions)
487 int a[] = {0, 2, 4, 1, 3, 5};
489 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
492TEST(SortUtilsHelpers, push2_fixedstack)
496 EXPECT_EQ(st.pop(), 1);
497 EXPECT_EQ(st.pop(), 2);
498 EXPECT_TRUE(st.is_empty());
501TEST(SortUtilsHelpers, quicksort_no_tail_pointer)
503 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
505 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
508TEST(SortUtilsHelpers, compare_tnode_direct)
513 EXPECT_TRUE(
cmp(
static_cast<Slinknc *
>(&n1), 5));
516TEST(SortUtilsHelpers, insert_sorted_dlink_and_list_insertion_sort)
528 insert_sorted<Cmp>(base, n2,
cmp);
529 insert_sorted<Cmp>(base, n0,
cmp);
530 insert_sorted<Cmp>(base, n1,
cmp);
534 Dnode<int> h2 = make_dnode_list({3, 1, 2, 0});
536 list_insertion_sort<Dlink, Cmp>(base2,
cmp);
540 delete_all_nodes(h2);
543TEST(SortUtilsHelpers, insert_sorted_htlist_and_list_insertion_sort)
555 for (
int x : {3, 1, 2, 0})
557 list_insertion_sort<HTList, Compare_Snodenc<int, Aleph::less<int>>>(
562TEST(SortUtilsHelpers, dlink_random_search_and_dlink_random_select)
564 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
571 ASSERT_NE(found,
nullptr);
572 EXPECT_EQ(found->get_data(), 3);
575 ASSERT_NE(sel,
nullptr);
576 EXPECT_EQ(
static_cast<Dnode<int> *
>(sel)->get_data(), 0);
581TEST(SortUtilsHelpers, binindex_explicit)
587TEST(SortUtilsHelpers, __random_select_raw_pointer)
589 int a[] = {4, 1, 3, 2, 0, 2};
590 std::vector<int>
expected(std::begin(a), std::end(a));
599TEST(SortUtilsHelpers, sift_up_and_sift_down_restore_min_heap)
611 sift_up<int, Aleph::less<int>>(a, 4,
cmp);
623 sift_down<int, Aleph::less<int>>(a, 3,
cmp);
628TEST(SortUtilsArraySorts, mergesort_pointer)
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)));
635TEST(SortUtilsArraySorts, quicksort_pointer)
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)));
642TEST(SortUtilsArraySorts, quicksort_rec_pointer)
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)));
649TEST(SortUtilsArraySorts, quicksort_rec_min_pointer)
651 int a[] = {5, 4, 3, 2, 1, 0, 0, 9};
653 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
656TEST(SortUtilsArraySorts, quicksort_insertion_pointer)
658 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
660 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
664 EXPECT_TRUE(std::is_sorted(std::begin(b), std::end(b)));
668TEST(SortUtilsArraySorts, introsort_pointer_basic)
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)));
675TEST(SortUtilsArraySorts, introsort_pointer_convenience)
677 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
679 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
682TEST(SortUtilsArraySorts, introsort_pointer_custom_compare)
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>()));
689TEST(SortUtilsArraySorts, introsort_dynarray)
693 for (
size_t i = 1; i < a.size(); ++i)
694 ASSERT_LE(a(i - 1), a(i));
697TEST(SortUtilsArraySorts, introsort_empty_and_single)
702 EXPECT_EQ(empty[0], 0);
707 EXPECT_EQ(single[0], 42);
714TEST(SortUtilsArraySorts, introsort_already_sorted)
716 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
718 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
721TEST(SortUtilsArraySorts, introsort_reverse_sorted)
723 int a[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
725 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
728TEST(SortUtilsArraySorts, introsort_all_equal)
730 int a[] = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
732 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
735TEST(SortUtilsArraySorts, introsort_large_array_forces_heapsort)
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);
745 EXPECT_TRUE(std::is_sorted(v.begin(), v.end()));
748TEST(SortUtilsArraySorts, introsort_dynarray_large)
751 const size_t n = 5000;
754 for (
size_t i = 0; i < n; ++i)
755 a(i) =
static_cast<int>(n - i);
758 for (
size_t i = 1; i < n; ++i)
759 ASSERT_LE(a(i - 1), a(i)) <<
"Failed at index " << i;
763TEST(SortUtilsArraySorts, introsort_pointer_begin_end)
765 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
767 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
770TEST(SortUtilsArraySorts, introsort_pointer_begin_end_partial)
772 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
778 EXPECT_TRUE(std::is_sorted(a + 2, a + 7));
782TEST(SortUtilsArraySorts, introsort_pointer_begin_end_custom_compare)
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>()));
789TEST(SortUtilsArraySorts, introsort_pointer_begin_end_empty)
798TEST(SortUtilsArraySorts, introsort_array_container)
810 for (
size_t i = 1; i < arr.
size(); ++i)
811 ASSERT_LE(arr(i - 1), arr(i));
814TEST(SortUtilsArraySorts, introsort_array_container_custom_compare)
817 for (
int i = 1; i <= 10; ++i)
822 for (
size_t i = 1; i < arr.
size(); ++i)
823 ASSERT_GE(arr(i - 1), arr(i));
826TEST(SortUtilsArraySorts, introsort_array_container_empty)
833TEST(SortUtilsArraySorts, introsort_array_container_single)
838 EXPECT_EQ(arr.
size(), 1u);
839 EXPECT_EQ(arr(0), 42);
842TEST(SortUtilsArraySorts, introsort_array_container_large)
844 const size_t n = 5000;
846 for (
size_t i = 0; i < n; ++i)
847 arr.
append(
static_cast<int>(n - i));
851 for (
size_t i = 1; i < n; ++i)
852 ASSERT_LE(arr(i - 1), arr(i)) <<
"Failed at index " << i;
864 vector<int> pdq_keys(
const string & pattern,
const size_t n,
const unsigned seed)
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")
876 else if (pattern ==
"reversed")
878 else if (pattern ==
"organ")
879 keys[i] = i <
m / 2 ? i :
m - i;
880 else if (pattern ==
"sawtooth")
884 if (pattern ==
"nearly")
885 for (
size_t k = 0; n > 1
and k < n / 50 + 1; ++
k)
887 const size_t x =
rng() % n;
888 const size_t y =
rng() % n;
894 const vector<string> pdq_patterns = {
"random",
"few",
"equal",
"sorted",
"reversed",
895 "organ",
"sawtooth",
"nearly"};
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};
902 template <
typename T>
903 void introsort_keeps_the_items(
const vector<T> & items)
908 introsort(a.data(), a.size(), [&total](
const T & x,
const T &
y)
916 for (
size_t k = 1; k <= total; k += std::max<size_t>(1, total / 400))
923 throw runtime_error(
"comparison failed");
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;
933TEST(SortUtilsArraySorts, introsort_gives_the_order_of_std_sort_on_every_pattern)
935 for (
const auto & pattern : pdq_patterns)
936 for (const size_t n : pdq_sizes)
938 auto a = pdq_keys(pattern, n, 1);
942 ASSERT_EQ(a,
expected) << pattern <<
", " << n <<
" items";
944 auto d = pdq_keys(pattern, n, 1);
946 introsort(d.data(), n, std::greater<int>());
947 ASSERT_EQ(d,
expected) << pattern <<
", " << n <<
" items, descending";
951TEST(SortUtilsArraySorts, introsort_sorts_pointers_by_their_targets)
953 for (
const auto & pattern : pdq_patterns)
954 for (const size_t n : pdq_sizes)
956 const auto keys = pdq_keys(pattern, n, 2);
957 vector<const int *> p(n);
958 for (
size_t i = 0; i < n; ++i)
960 introsort(p.data(), n, [](
const int * x,
const int *
y) { return *x < *y; });
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());
967 for (
size_t i = 0; i < n; ++i)
968 ASSERT_EQ(p[i], &
keys[i]) << pattern <<
", " << n <<
" items";
972TEST(SortUtilsArraySorts, introsort_sorts_strings)
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),
979 for (
const int k : pdq_keys(pattern, n, 3))
984 ASSERT_EQ(a,
expected) << pattern <<
", " << n <<
" items";
988TEST(SortUtilsArraySorts, introsort_sorts_items_that_can_only_move)
990 vector<unique_ptr<int>> a;
992 for (
const int k : pdq_keys(
"random", 3000, 4))
994 a.push_back(make_unique<int>(
k));
995 items.push_back(a.back().get());
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]);
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);
1010TEST(SortUtilsArraySorts, introsort_sorts_only_its_range)
1012 for (
const size_t n : {size_t(24), size_t(200), size_t(5000)})
1014 auto keys = pdq_keys(
"random", n, 5);
1015 vector<int> a(n + 20, numeric_limits<int>::max());
1016 for (
size_t i = n + 10; i < n + 20; ++i)
1017 a[i] = numeric_limits<int>::min();
1018 std::copy(
keys.begin(),
keys.end(), a.begin() + 10);
1019 introsort(a.data(), 10L,
static_cast<long>(n + 9));
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)
1025 EXPECT_EQ(a[i], numeric_limits<int>::max());
1026 EXPECT_EQ(a[n + 10 + i], numeric_limits<int>::min());
1033TEST(SortUtilsArraySorts, introsort_takes_linear_comparisons_on_ordered_ranges)
1035 const size_t n = 100000;
1036 for (
const string pattern : {
"sorted",
"reversed",
"equal"})
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)
1045 EXPECT_TRUE(std::is_sorted(a.begin(), a.end())) << pattern;
1046 EXPECT_LE(comparisons, 4 * n) << pattern;
1054TEST(SortUtilsArraySorts, introsort_bounds_the_comparisons_of_a_killer_adversary)
1056 const int n = 20000;
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)
1065 value[x == candidate ? x :
y] = frozen++;
1066 if (
value[x] == gas)
1068 else if (
value[
y] == gas)
1072 vector<int> items(n);
1073 for (
int i = 0; i < n; ++i)
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)));
1084TEST(SortUtilsArraySorts, introsort_keeps_the_items_if_the_comparison_throws)
1086 for (
const string pattern : {
"random",
"few",
"sorted",
"reversed",
"organ",
"nearly"})
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)
1093 introsort_keeps_the_items(strings);
1103TEST(SortUtilsArraySorts, heapsorts_let_a_throwing_comparison_through)
1105 constexpr size_t n = 600;
1106 size_t count = 0, fail_at = 0;
1107 auto tick = [&
count, &fail_at]
1109 if (++
count == fail_at)
1110 throw runtime_error(
"comparison failed");
1114 int solid = 0, candidate = 0;
1115 const int gas =
static_cast<int>(n);
1116 auto adversary = [&](
const int x,
const int y)
1119 if (val[x] == gas
and val[
y] == gas)
1120 val[x == candidate ? x :
y] = solid++;
1123 else if (val[
y] == gas)
1125 return val[x] < val[
y];
1127 auto sort_against_the_adversary = [&](
const size_t k)
1132 solid = candidate = 0;
1134 for (
size_t i = 0; i < n; ++i)
1135 a[i] =
static_cast<int>(i);
1138 introsort(a.data(), a.size(), adversary);
1140 catch (
const runtime_error &)
1142 std::sort(a.begin(), a.end());
1143 for (
size_t i = 0; i < n; ++i)
1144 if (a[i] !=
static_cast<int>(i))
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;
1156 auto throwing_less = [&tick](
const int x,
const int y)
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)})
1165 vector<int> a = pdq_keys(
"random", 200, 3);
1168 EXPECT_THROW(
sort(a.data(), a.size(), throwing_less), runtime_error) <<
"at comparison " <<
k;
1172TEST(SortUtilsArraySorts, heapsort_dynarray)
1176 for (
size_t i = 1; i < a.size(); ++i)
1177 ASSERT_LE(a(i - 1), a(i));
1180TEST(SortUtilsArraySorts, quicksort_op_dynarray)
1184 for (
size_t i = 1; i < a.size(); ++i)
1185 ASSERT_LE(a(i - 1), a(i));
1188TEST(SortUtilsArraySorts, quicksort_op_empty)
1195TEST(SortUtilsArraySorts, shellsort_dynarray)
1199 for (
size_t i = 1; i < a.
size(); ++i)
1200 ASSERT_LE(a(i - 1), a(i));
1203TEST(SortUtilsArraySorts, quicksort_dynarray)
1207 for (
size_t i = 1; i < a.
size(); ++i)
1208 ASSERT_LE(a(i - 1), a(i));
1211TEST(SortUtilsArraySorts, quicksort_rec_dynarray)
1215 for (
size_t i = 1; i < a.
size(); ++i)
1216 ASSERT_LE(a(i - 1), a(i));
1227 DynArray<int> dynarray_keys(
const string & pattern,
const size_t n)
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")
1237 else if (pattern ==
"reversed")
1239 else if (pattern ==
"organ")
1248 template <
class Sort>
1249 size_t sort_dynarray(
const string & pattern,
const size_t n, Sort
sort)
1251 auto a = dynarray_keys(pattern, n);
1253 for (
size_t i = 0; i < n; ++i)
1257 size_t comparisons = 0;
1258 sort(a, [&comparisons](
const int x,
const int y)
1264 bool same = a.
size() == n;
1265 for (
size_t i = 0; same
and i < n; ++i)
1267 EXPECT_TRUE(same) << pattern <<
", " << n <<
" items";
1280TEST(SortUtilsArraySorts, sorts_of_a_dynarray_give_the_order_of_std_sort)
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)})
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);
1293TEST(SortUtilsArraySorts, sorts_of_a_dynarray_split_sorted_and_reversed_input_in_halves)
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"})
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;
1306TEST(SortUtilsListSorts, mergesort_dynlist)
1313TEST(SortUtilsListSorts, mergeinsertsort_dynlist)
1315 DynList<int> l = make_dynlist({9, 8, 7, 6, 5, 4, 3, 2, 1, 0});
1320TEST(SortUtilsListSorts, insertion_sort_dynlist_rvalue)
1328TEST(SortUtilsListSorts, mergesort_dynlist_rvalue)
1336TEST(SortUtilsListSorts, quicksort_dynlist)
1345TEST(SortUtilsListSorts, merge_lists_dynlist)
1355 EXPECT_EQ(
out.size(), 6u);
1356 EXPECT_EQ(
out.get_first(), 0);
1357 EXPECT_EQ(
out.get_last(), 5);
1360TEST(SortUtilsListSorts, merge_lists_dnode)
1362 auto l1 = make_dnode_list({0, 2, 4});
1363 auto l2 = make_dnode_list({1, 3, 5});
1370 EXPECT_FALSE(
out.is_empty());
1374 EXPECT_EQ(it.get_curr_ne()->get_data(),
expected);
1377 delete_all_nodes(
out);
1380TEST(SortUtilsDyndlistSorts, mergesort_dyndlist)
1390 struct Keyed {
int key;
int seq; };
1394 bool operator()(
const Keyed & a,
const Keyed & b)
const noexcept
1396 return a.key < b.key;
1401 template <
class Container>
1402 bool keeps_order_of_equals(
const Container & c)
1404 const Keyed * prev =
nullptr;
1405 for (
const Keyed & x : c)
1407 if (prev !=
nullptr and prev->key == x.key
and prev->seq > x.seq)
1415 template <
class Container>
1418 const Keyed * prev =
nullptr;
1419 for (
const Keyed & x : c)
1421 if (prev !=
nullptr and By_Key()(x, *prev))
1431TEST(SortUtilsStability, mergesort_keeps_the_order_of_equal_items)
1433 std::mt19937 gen(3);
1434 for (
int round = 0; round < 50; ++round)
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});
1444 for (
const Keyed & x : items)
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));
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()));
1471 bool operator()(
const int a,
const int b)
const
1474 throw std::runtime_error(
"comparison failed");
1480 template <
class Container>
1481 std::vector<int> sorted_items(
const Container & c)
1484 for (
const int x : c)
1486 std::sort(v.begin(), v.end());
1494TEST(SortUtilsStability, mergesort_of_a_list_keeps_its_items_if_the_comparison_throws)
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);
1505 for (
const int x : items)
1508 ASSERT_EQ(sorted_items(list),
all);
1510 ASSERT_GT(total, 0);
1512 for (
int at = 1; at <= total; ++at)
1517 for (
const int x : items)
1524 EXPECT_THROW(
mergesort(list, Throws_At{&
count, at}), std::runtime_error);
1526 EXPECT_THROW(
mergesort(dlist, Throws_At{&
count, at}), std::runtime_error);
1528 EXPECT_EQ(sorted_items(list),
all);
1529 EXPECT_EQ(sorted_items(dlist),
all);
1537 template <
class List,
class Sort>
1538 void keeps_its_items_if_the_comparison_throws(
const std::vector<int> & items,
1541 const std::vector<int>
all = sorted_items(items);
1545 for (
const int x : items)
1547 sort(list, Throws_At{&total, -1});
1548 std::vector<int> got;
1549 for (
const int x : list)
1551 ASSERT_EQ(got,
all);
1553 ASSERT_GT(total, 0);
1555 for (
int at = 1; at <= total; ++at)
1559 for (
const int x : items)
1562 EXPECT_THROW(
sort(list, Throws_At{&
count, at}), std::runtime_error);
1563 EXPECT_EQ(sorted_items(list),
all);
1571TEST(SortUtilsStability, every_sort_of_a_list_keeps_its_items_if_the_comparison_throws)
1573 std::mt19937 gen(13);
1574 std::vector<int> items;
1575 for (
int i = 0; i < 100; ++i)
1576 items.push_back(
int(gen() % 20));
1579 SCOPED_TRACE(
"mergesort<DynList, int>()");
1580 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (
auto &
l,
const Throws_At & c)
1582 mergesort<DynList, int, Throws_At>(
l, c);
1586 SCOPED_TRACE(
"mergesort<DynDlist, int>()");
1587 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (
auto &
l,
const Throws_At & c)
1589 mergesort<DynDlist, int, Throws_At>(
l, c);
1593 SCOPED_TRACE(
"mergeinsertsort(DynList &)");
1594 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (
auto &
l,
const Throws_At & c)
1600 SCOPED_TRACE(
"mergeinsertsort(DynDlist &)");
1601 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (
auto &
l,
const Throws_At & c)
1607 SCOPED_TRACE(
"insertion_sort(DynList &)");
1608 keeps_its_items_if_the_comparison_throws<DynList<int>>(items, [] (
auto &
l,
const Throws_At & c)
1614 SCOPED_TRACE(
"insertion_sort(DynDlist &)");
1615 keeps_its_items_if_the_comparison_throws<DynDlist<int>>(items, [] (
auto &
l,
const Throws_At & c)
1624TEST(SortUtilsStability, insertion_sort_of_a_dyndlist_keeps_the_order_of_equal_items)
1626 std::mt19937 gen(5);
1627 for (
int n = 0; n <= 60; ++n)
1632 for (
int i = 0; i < n; ++i)
1634 const Keyed x{int(gen() % 5), i};
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));
1651 struct Strings_Throw_At
1656 bool operator()(
const std::string & a,
const std::string & b)
const
1659 throw std::runtime_error(
"comparison failed");
1668TEST(SortUtilsStability, mergesort_of_an_array_keeps_its_items_if_the_comparison_throws)
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());
1678 std::vector<std::string> a = items;
1679 mergesort(a.data(), 0,
long(a.size()) - 1, Strings_Throw_At{&total, -1});
1682 ASSERT_GT(total, 0);
1684 for (
int at = 1; at <= total; ++at)
1687 std::vector<std::string> a = items;
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());
1700 struct Throwing_Less
1702 static inline int count = 0;
1703 static inline int at = 0;
1706 bool operator < (
const Throwing_Less & other)
const
1709 throw std::runtime_error(
"comparison failed");
1710 return value < other.value;
1714 template <
class Container>
1715 std::vector<int> sorted_values(
const Container & c)
1718 for (
const Throwing_Less & x : c)
1719 v.push_back(x.
value);
1720 std::sort(v.begin(), v.end());
1726 std::declval<const Throwing_Less &>())));
1731TEST(SortUtilsStability, what_the_less_than_of_the_items_throws_reaches_the_caller)
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);
1738 Throwing_Less::count = 0;
1739 Throwing_Less::at = 0;
1742 for (
const int v : values)
1743 list.append(Throwing_Less{v});
1745 ASSERT_EQ(sorted_values(list),
all);
1747 const int total = Throwing_Less::count;
1748 ASSERT_GT(total, 0);
1750 for (
int at = 1; at <= total; ++at)
1755 std::vector<Throwing_Less> array;
1756 for (
const int v : values)
1758 list.
append(Throwing_Less{v});
1759 dlist.
append(Throwing_Less{v});
1760 array.push_back(Throwing_Less{v});
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;
1772 EXPECT_EQ(sorted_values(list),
all);
1773 EXPECT_EQ(sorted_values(dlist),
all);
1774 EXPECT_EQ(sorted_values(array),
all);
1778TEST(SortUtilsDyndlistSorts, search_extreme_min)
1782 ASSERT_NE(p,
nullptr);
1786TEST(SortUtilsDyndlistSorts, random_select_dyndlist)
1790 ASSERT_NE(p,
nullptr);
1794 ASSERT_NE(p,
nullptr);
1798TEST(SortUtilsDyndlistSorts, random_search_dyndlist)
1803 ASSERT_NE(p,
nullptr);
1807 EXPECT_EQ(p,
nullptr);
1810TEST(SortUtilsDnodeDlinkAlgorithms, random_select_and_random_search_on_dlink)
1812 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1814 auto * n0 = random_select<int>(
h, 0);
1815 ASSERT_NE(n0,
nullptr);
1816 EXPECT_EQ(n0->get_data(), 0);
1818 auto * nmax = random_select<int>(
h, 5);
1819 ASSERT_NE(nmax,
nullptr);
1820 EXPECT_EQ(nmax->get_data(), 4);
1822 auto * nfound = random_search<int>(
h, 3);
1823 ASSERT_NE(nfound,
nullptr);
1824 EXPECT_EQ(nfound->get_data(), 3);
1826 auto * nmiss = random_search<int>(
h, 99);
1827 EXPECT_EQ(nmiss,
nullptr);
1829 delete_all_nodes(
h);
1832TEST(SortUtilsHTListPath, quicksort_htlist_via_dynlist)
1839TEST(SortUtilsSearchSequential, sequential_search_raw_array)
1841 int a[] = {4, 1, 3, 2, 0, 2};
1846TEST(SortUtilsSearchSequential, sequential_search_dynarray)
1853TEST(SortUtilsSearchSequential, sequential_search_dynlist)
1857 ASSERT_NE(p,
nullptr);
1861 EXPECT_EQ(p,
nullptr);
1864TEST(SortUtilsSearchSequential, sequential_search_const_dynlist)
1868 ASSERT_NE(p,
nullptr);
1872 EXPECT_EQ(p,
nullptr);
1875TEST(SortUtilsSearchSequential, sequential_search_dyndlist)
1879 ASSERT_NE(p,
nullptr);
1882 EXPECT_EQ(p,
nullptr);
1885TEST(SortUtilsSearchSequential, sequential_search_dnode)
1887 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1890 ASSERT_NE(n,
nullptr);
1891 EXPECT_EQ(n->get_data(), 3);
1894 EXPECT_EQ(n,
nullptr);
1896 delete_all_nodes(
h);
1899TEST(SortUtilsSearchExtreme, search_extreme_dnode_min)
1901 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1903 ASSERT_NE(n,
nullptr);
1904 EXPECT_EQ(n->get_data(), 0);
1905 delete_all_nodes(
h);
1908TEST(SortUtilsSearchExtreme, search_min_max_raw_array)
1910 int a[] = {4, 1, 3, 2, 0, 2};
1915TEST(SortUtilsSearchExtreme, search_extreme_and_search_max_dynarray)
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);
1922TEST(SortUtilsSearchExtreme, search_min_max_dyndlist)
1927 ASSERT_NE(mn,
nullptr);
1928 ASSERT_NE(mx,
nullptr);
1933TEST(SortUtilsSearchExtreme, search_extreme_dynlist_min_max)
1938 ASSERT_NE(mn,
nullptr);
1939 ASSERT_NE(mx,
nullptr);
1944TEST(SortUtilsSearchExtreme, search_extreme_const_dynlist_min_max)
1949 ASSERT_NE(mn,
nullptr);
1950 ASSERT_NE(mx,
nullptr);
1958TEST(SortUtilsSearchExtreme, search_min_max_dynlist)
1963 ASSERT_NE(mn,
nullptr);
1964 ASSERT_NE(mx,
nullptr);
1969TEST(SortUtilsDnodeSorts, selection_insertion_quick_merge)
1972 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1975 delete_all_nodes(
h);
1979 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1982 delete_all_nodes(
h);
1986 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1989 delete_all_nodes(
h);
1993 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
1996 delete_all_nodes(
h);
2000TEST(SortUtilsDlinkSorts, quicksort_dlink)
2002 auto h = make_dnode_list({4, 1, 3, 2, 0, 2});
2011 delete_all_nodes(
h);
2014TEST(SortUtilsSearch, binary_search_dup_and_bsearch)
2019 ASSERT_EQ(idxs.size(), 3u);
2020 EXPECT_EQ(idxs.get_first(), 1u);
2021 EXPECT_EQ(idxs.get_last(), 3u);
2024 ASSERT_NE(p,
nullptr);
2026 EXPECT_EQ(
bsearch(a, 99),
nullptr);
2029TEST(SortUtilsSearch, binary_search_dup_boundary_cases)
2034 ASSERT_EQ(idxs.size(), 3u);
2035 EXPECT_EQ(idxs.get_first(), 0u);
2036 EXPECT_EQ(idxs.get_last(), 2u);
2042 ASSERT_EQ(idxs.size(), 3u);
2043 EXPECT_EQ(idxs.get_first(), 3u);
2044 EXPECT_EQ(idxs.get_last(), 5u);
2048TEST(SortUtilsSearch, binary_search_dup_custom_compare_descending)
2053 ASSERT_EQ(idxs.size(), 3u);
2054 EXPECT_EQ(idxs.get_first(), 2u);
2055 EXPECT_EQ(idxs.get_last(), 4u);
2058 ASSERT_EQ(idxs.size(), 2u);
2059 EXPECT_EQ(idxs.get_first(), 6u);
2060 EXPECT_EQ(idxs.get_last(), 7u);
2063TEST(SortUtilsSearch, bsearch_dup_custom_compare_descending)
2067 ASSERT_EQ(ps.size(), 3u);
2070 ASSERT_NE(p,
nullptr);
2075TEST(SortUtilsIndexBuild, build_index_and_build_index_ptr)
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)));
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));
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));
2100TEST(SortUtilsIndexBuild, build_index_supports_std_vector)
2102 std::vector<int> a = {3, 1, 2, 1, 0};
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)]);
2112TEST(SortUtilsIndexBuild, stable_build_index_preserves_equal_order_dynarray)
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);
2127TEST(SortUtilsIndexBuild, stable_build_index_ptr_preserves_equal_order)
2133 static_assert(std::is_same_v<
decltype(ptrs),
Array<int *>>);
2134 ASSERT_EQ(ptrs.size(), a.size());
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));
2146 ASSERT_EQ(cptrs.size(), a.size());
2147 for (
size_t i = 0; i < ptrs.size(); ++i)
2148 EXPECT_EQ(cptrs(i), ptrs(i));
2151TEST(SortUtilsIndexBuild, stable_build_index_ptr_preserves_large_duplicate_groups)
2155 for (
size_t i = 0; i < 75; ++i)
2156 a(i) =
static_cast<int>((i * 17) % 5);
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)
2164 ASSERT_LE(*ptrs(i - 1), *ptrs(i));
2165 if (*ptrs(i - 1) == *ptrs(i))
2167 EXPECT_LT(ptrs(i - 1), ptrs(i))
2168 <<
"equal-valued elements must keep their original relative order";
2173TEST(SortUtilsIndexBuild, stable_build_index_preserves_large_duplicate_groups)
2176 for (
size_t i = 0; i < 75; ++i)
2177 a.push_back(
static_cast<int>((i * 17) % 5));
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)
2185 ASSERT_LE(a[idx(i - 1)], a[idx(i)]);
2186 if (a[idx(i - 1)] == a[idx(i)])
2188 EXPECT_LT(idx(i - 1), idx(i));
2193TEST(SortUtilsIndexBuild, stable_build_index_exhaustive_matches_stable_sort_reference)
2195 expect_stable_build_index_matches_reference_exhaustively(std::less<int>());
2198TEST(SortUtilsIndexBuild, stable_build_index_exhaustive_matches_descending_stable_sort_reference)
2200 expect_stable_build_index_matches_reference_exhaustively(std::greater<int>());
2203TEST(SortUtilsIndexBuild, stable_build_index_supports_std_vector)
2205 std::vector<int> a = {2, 1, 2, 1, 2};
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);
2218TEST(SortUtilsSlinkncPath, sequential_search_and_search_extreme_on_slinknc)
2231 ASSERT_NE(found,
nullptr);
2232 EXPECT_EQ(
static_cast<Snodenc<int>*
>(found)->get_data(), 3);
2235 EXPECT_EQ(missing,
nullptr);
2238 ASSERT_NE(extreme_min,
nullptr);
2239 EXPECT_EQ(
static_cast<Snodenc<int>*
>(extreme_min)->get_data(), 0);
2245TEST(SortUtilsSlinkncPath, sequential_search_default_equal_on_slinknc)
2255 auto * found = sequential_search<int>(head, 1);
2256 ASSERT_NE(found,
nullptr);
2257 EXPECT_EQ(found->to_data<
int>(), 1);
2259 auto * missing = sequential_search<int>(head, 99);
2260 EXPECT_EQ(missing,
nullptr);
2266TEST(SortUtilsDlinkPath, sequential_search_and_selection_sort_on_dlink)
2268 auto h = make_dnode_list({3, 1, 2, 0});
2271 auto * found = sequential_search<int>(base, 2);
2272 ASSERT_NE(found,
nullptr);
2273 EXPECT_EQ(
static_cast<Dnode<int>*
>(found)->get_data(), 2);
2277 ASSERT_NE(mn,
nullptr);
2278 EXPECT_EQ(mn->get_data(), 0);
2280 delete_all_nodes(
h);
2283TEST(SortUtilsRandomSearch, random_search_raw_and_dynarray)
2285 int a[] = {4, 1, 3, 2, 0, 2};
2288 EXPECT_EQ(a[idx], 3);
2292 idx =
random_search(d, 3, 0,
static_cast<long>(d.size() - 1));
2294 EXPECT_EQ(d(idx), 3);
2298TEST(SortUtilsRandomSelect, random_select_array_container)
2301 for (
int x : {4, 1, 3, 2, 0, 2})
2308TEST(SortUtilsRandomSelect, random_select_out_of_range_and_empty)
2327 int b[] = {4, 1, 3};
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);
2336 EXPECT_EQ(random_select<int>(
h, 0),
nullptr);
2337 EXPECT_EQ(random_select<int>(
h, 1),
nullptr);
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);
2353 auto l = make_dyndlist({4, 1});
2358TEST(SortUtilsSearch, binary_search_insertion_point_container)
2371TEST(SortUtilsSearch, binary_search_insertion_point_raw)
2373 int a[] = {0, 2, 4, 6};
2381TEST(SortUtilsSearch, binary_search_rec_insertion_point_raw)
2383 int a[] = {0, 2, 4, 6};
2391TEST(SortUtilsSearch, random_select_dynarray_and_raw)
2397 int b[] = {4, 1, 3, 2, 0, 2};
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);
2405TEST(SortUtilsSearch, binary_search_ptr_container)
2410 for (
size_t i = 0; i < a.size(); ++i)
2420TEST(SortUtilsSearch, bsearch_dup_and_binindex_dup)
2424 ASSERT_EQ(ptrs.size(), 3u);
2426 ASSERT_NE(p, nullptr);
2429 ASSERT_EQ(idxs.size(), 3u);
2430 EXPECT_EQ(idxs.get_first(), 1);
2431 EXPECT_EQ(idxs.get_last(), 3);
2434TEST(SortUtilsSearch, bsearch_dup_ptr_container_custom_compare_descending)
2439 for (
size_t i = 0; i < a.size(); ++i)
2443 ASSERT_EQ(dup.size(), 3u);
2446 ASSERT_NE(p,
nullptr);
2451TEST(SortUtilsSearch, binindex_dup_ptr_container_custom_compare_descending)
2456 for (
size_t i = 0; i < a.size(); ++i)
2460 ASSERT_EQ(idxs.size(), 3u);
2461 EXPECT_EQ(idxs.get_first(), 2);
2462 EXPECT_EQ(idxs.get_last(), 4);
2465TEST(SortUtilsSearch, bsearch_dup_ptr_container)
2470 for (
size_t i = 0; i < a.size(); ++i)
2473 auto found =
bsearch(ptrs, 1);
2474 ASSERT_NE(found,
nullptr);
2475 EXPECT_EQ(*found, 1);
2478 ASSERT_EQ(dup.size(), 3u);
2481 ASSERT_NE(p,
nullptr);
2486TEST(SortUtilsSearch, binindex_dup_ptr_container)
2491 for (
size_t i = 0; i < a.size(); ++i)
2495 ASSERT_EQ(idxs.size(), 3u);
2496 EXPECT_EQ(idxs.get_first(), 1);
2497 EXPECT_EQ(idxs.get_last(), 3);
2500TEST(SortUtilsSearch, binary_search_ptr_container_custom_compare)
2505 for (
size_t i = 0; i < a.size(); ++i)
2514TEST(SortUtilsSearch, binary_search_ptr_container_range_less)
2519 for (
size_t i = 0; i < a.size(); ++i)
2530TEST(SortUtilsSearch, binary_search_ptr_container_range_greater)
2535 for (
size_t i = 0; i < a.size(); ++i)
2548TEST(SortUtilsCountingSort, basic_sort_by_identity)
2552 sa[0] = 3; sa[1] = 0; sa[2] = 4; sa[3] = 1; sa[4] = 2;
2555 [](
size_t idx) ->
int {
return static_cast<int>(idx); });
2557 for (
size_t i = 0; i < 5; ++i)
2558 EXPECT_EQ(sa[i], i);
2569TEST(SortUtilsCountingSort, stability)
2575 sa[0] = 0; sa[1] = 1; sa[2] = 2; sa[3] = 3;
2577 std::array<int, 4>
keys = {2, 1, 1, 0};
2579 [&](
size_t idx) ->
int {
return keys[idx]; });
2582 EXPECT_EQ(sa[0], 3u);
2583 EXPECT_EQ(sa[1], 1u);
2584 EXPECT_EQ(sa[2], 2u);
2585 EXPECT_EQ(sa[3], 0u);
2588TEST(SortUtilsCountingSort, negative_keys)
2592 sa[0] = 0; sa[1] = 1; sa[2] = 2; sa[3] = 3;
2594 std::array<int, 4>
keys = {0, -1, 2, -2};
2596 [&](
size_t idx) ->
int {
return keys[idx]; });
2599 EXPECT_EQ(sa[0], 3u);
2600 EXPECT_EQ(sa[1], 1u);
2601 EXPECT_EQ(sa[2], 0u);
2602 EXPECT_EQ(sa[3], 2u);
2605TEST(SortUtilsCountingSort, single_element)
2612 [](
size_t) ->
int {
return 0; });
2613 EXPECT_EQ(sa[0], 42u);
2616TEST(SortUtilsCountingSort, empty)
2621 [](
size_t) ->
int {
return 0; });
2625TEST(SortUtilsCountingSort, invalid_key_interval_throws)
2633 [](
size_t) ->
int {
return 0; }),
2637TEST(SortUtilsCountingSort, key_out_of_range_throws)
2646 [](
size_t idx) ->
int {
return idx == 0 ? 0 : 2; }),
2650TEST(SortUtilsCountingSort, insufficient_buffers_throw)
2658 [](
size_t idx) ->
int {
return static_cast<int>(idx); }),
2662TEST(SortUtilsCountingSortGeneric, dynarray_signed_with_negatives)
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));
2673TEST(SortUtilsCountingSortGeneric, array_unsigned_values)
2676 for (
unsigned int x : {7u, 0u, 3u, 7u, 1u, 2u})
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);
2688TEST(SortUtilsCountingSortGeneric, raw_pointer_and_nullptr_contract)
2690 int a[] = {4, 1, 3, 0, 2};
2692 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2694 EXPECT_THROW((counting_sort<int>(
nullptr, 1)), std::invalid_argument);
2695 EXPECT_NO_THROW((counting_sort<int>(
nullptr, 0)));
2698TEST(SortUtilsCountingSortGeneric, c_array_overload)
2700 int a[] = {5, 1, 4, 2, 3, 0};
2702 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2705TEST(SortUtilsCountingSortGeneric, dynarray_support)
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);
2717TEST(SortUtilsCountingSortGeneric, empty_and_singleton)
2726 ASSERT_EQ(a.
size(), 1u);
2730TEST(SortUtilsCountingSortGeneric, dynlist_support)
2735 std::array<int, 6>
expected = {-1, -1, 0, 2, 3, 4};
2738 EXPECT_EQ(it.get_curr(),
expected[i]);
2742TEST(SortUtilsCountingSortGeneric, dynlist_preserves_nodes)
2745 const auto before = dynlist_node_addresses(
l);
2747 const auto after = dynlist_node_addresses(
l);
2748 expect_same_dynarray(before, after);
2751TEST(SortUtilsCountingSortGeneric, dyndlist_support)
2756 std::array<int, 6>
expected = {-2, 0, 1, 3, 7, 7};
2759 EXPECT_EQ(it.get_curr(),
expected[i]);
2763TEST(SortUtilsCountingSortGeneric, dyndlist_preserves_nodes)
2766 const auto before = dyndlist_node_addresses(
l);
2768 const auto after = dyndlist_node_addresses(
l);
2769 expect_same_dynarray(before, after);
2772TEST(SortUtilsCountingSortGeneric, huge_range_throws)
2777 a(1) = std::numeric_limits<unsigned long long>::max();
2781TEST(SortUtilsRadixSort, dynarray_signed_basic)
2785 for (
size_t i = 1; i < a.
size(); ++i)
2786 ASSERT_LE(a(i - 1), a(i));
2789TEST(SortUtilsRadixSort, dynarray_with_negatives)
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));
2800TEST(SortUtilsRadixSort, array_container)
2803 for (
int x : {9, 1, 8, 2, 7, 3, 6, 4, 5, 0})
2807 for (
size_t i = 1; i < a.
size(); ++i)
2808 ASSERT_LE(a(i - 1), a(i));
2811TEST(SortUtilsRadixSort, raw_pointer)
2813 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
2815 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2818TEST(SortUtilsRadixSort, c_array_overload)
2820 int a[] = {9, 1, 8, 2, 7, 3, 6, 4, 5, 0};
2822 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
2825TEST(SortUtilsRadixSort, raw_pointer_nullptr_contract)
2827 EXPECT_THROW((radix_sort<int>(
nullptr, 1)), std::invalid_argument);
2828 EXPECT_NO_THROW((radix_sort<int>(
nullptr, 0)));
2831TEST(SortUtilsRadixSort, dynlist_support)
2836 std::array<int, 6>
expected = {-5, -1, 0, 2, 3, 3};
2839 EXPECT_EQ(it.get_curr(),
expected[i]);
2843TEST(SortUtilsRadixSort, dynlist_preserves_nodes)
2846 const auto before = dynlist_node_addresses(
l);
2848 const auto after = dynlist_node_addresses(
l);
2849 expect_same_dynarray(before, after);
2852TEST(SortUtilsRadixSort, dyndlist_support)
2857 std::array<int, 6>
expected = {-2, -2, 0, 1, 7, 10};
2860 EXPECT_EQ(it.get_curr(),
expected[i]);
2864TEST(SortUtilsRadixSort, dyndlist_preserves_nodes)
2867 const auto before = dyndlist_node_addresses(
l);
2869 const auto after = dyndlist_node_addresses(
l);
2870 expect_same_dynarray(before, after);
2873TEST(SortUtilsRadixSort, signed_extremes)
2877 a(0) = std::numeric_limits<int>::max();
2879 a(2) = std::numeric_limits<int>::min();
2881 a(4) = std::numeric_limits<int>::max();
2882 a(5) = std::numeric_limits<int>::min();
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));
2894TEST(SortUtilsRadixSort, unsigned_values)
2897 for (
unsigned int x : {std::numeric_limits<unsigned int>::max(),
2898 0u, 10u, 1u, 1024u, 10u})
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));
2912TEST(SortUtilsRadixSort, empty_and_singleton)
2916 EXPECT_EQ(d.
size(), 0u);
2921 ASSERT_EQ(a.
size(), 1u);
2925TEST(SortUtilsRandomSelect, duplicates_three_way_partition)
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};
2931 for (
size_t i = 0; i < v.
size(); ++i)
2935 EXPECT_EQ(res,
expected[i]) <<
"Mismatch at index " << i;
2939TEST(SortUtilsRandomSelect, identical_elements)
2942 for (
int i = 0; i < 100; ++i)
2945 for (
size_t i = 0; i < v.
size(); i += 10)
2949 EXPECT_EQ(res, 42) <<
"Mismatch at index " << i;
2953TEST(SortUtilsRandomSelect, sorted_and_reverse_sorted)
2956 for (
int i = 0; i < 50; ++i)
2960 for (
int i = 49; i >= 0; --i)
2963 for (
size_t i = 0; i < v.
size(); i += 5)
2968 EXPECT_EQ(
Aleph::random_select(©_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(©_rev(0),
static_cast<long>(i),
static_cast<long>(copy_rev.
size()), std::less<int>()),
static_cast<int>(i));
2973TEST(SortUtilsRandomSelect, RandomizedSeededProperty)
2975 std::mt19937 gen(42);
2976 for (
int iter = 0; iter < 100; ++iter)
2978 const size_t N = std::uniform_int_distribution<size_t>(1, 200)(gen);
2981 for (
size_t i = 0; i <
N; ++i)
2983 int val = std::uniform_int_distribution<int>(-1000, 1000)(gen);
2989 const long k = std::uniform_int_distribution<long>(0,
static_cast<long>(
N) - 1)(gen);
2992 EXPECT_EQ(res,
expected[
k]) <<
"Mismatch at iter " << iter <<
" rank " <<
k <<
" N " <<
N;
3000TEST(BucketSort, float_uniform)
3002 constexpr size_t N = 500;
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)
3011 for (
size_t i = 1; i <
N; ++i)
3012 ASSERT_LE(a(i - 1), a(i));
3015TEST(BucketSort, float_with_negatives)
3017 constexpr size_t N = 300;
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)
3026 for (
size_t i = 1; i <
N; ++i)
3027 ASSERT_LE(a(i - 1), a(i));
3030TEST(BucketSort, double_support)
3032 constexpr size_t N = 200;
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)
3041 for (
size_t i = 1; i <
N; ++i)
3042 ASSERT_LE(a(i - 1), a(i));
3045TEST(BucketSort, descending_order)
3047 constexpr size_t N = 100;
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)
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);
3060TEST(BucketSort, custom_bucket_key)
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;
3066 auto key = [](
const int & val) ->
size_t
3068 return static_cast<size_t>(val / 10);
3072 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3075TEST(BucketSort, custom_bucket_key_move_only_pointer)
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;
3089 static_assert(not
std::is_copy_constructible_v<MoveOnlyInt>);
3090 static_assert(not
std::is_copy_assignable_v<MoveOnlyInt>);
3093 MoveOnlyInt(7), MoveOnlyInt(1), MoveOnlyInt(4), MoveOnlyInt(0),
3094 MoveOnlyInt(6), MoveOnlyInt(2), MoveOnlyInt(5), MoveOnlyInt(3)
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
3100 return static_cast<size_t>(x.value / 2);
3102 auto cmp = [](
const MoveOnlyInt & lhs,
const MoveOnlyInt & rhs)
3104 return lhs.value < rhs.value;
3109 for (
size_t i = 1; i < n; ++i)
3113TEST(BucketSort, dynarray_support)
3115 constexpr size_t N = 100;
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)
3124 for (
size_t i = 1; i <
N; ++i)
3125 ASSERT_LE(a(i - 1), a(i));
3128TEST(BucketSort, array_support)
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)
3137 for (
size_t i = 1; i < a.
size(); ++i)
3138 ASSERT_LE(a(i - 1), a(i));
3141TEST(BucketSort, c_array_overload)
3143 double a[] = {3.5, 1.2, 4.8, 0.3, 2.7, 1.9, 4.1, 0.1};
3145 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3148TEST(BucketSort, dynlist_support)
3159 double prev = -std::numeric_limits<double>::infinity();
3162 EXPECT_GE(it.get_curr(), prev);
3163 prev = it.get_curr();
3167TEST(BucketSort, empty_and_singleton)
3171 EXPECT_EQ(d.
size(), 0u);
3177 ASSERT_EQ(s.
size(), 1u);
3178 EXPECT_FLOAT_EQ(s(0), 42.0f);
3181TEST(BucketSort, all_equal)
3183 constexpr size_t N = 50;
3186 for (
size_t i = 0; i <
N; ++i)
3190 for (
size_t i = 0; i <
N; ++i)
3191 EXPECT_FLOAT_EQ(a(i), 7.7f);
3194TEST(BucketSort, reverse_sorted_input)
3196 constexpr size_t N = 100;
3199 for (
size_t i = 0; i <
N; ++i)
3200 a(i) =
static_cast<double>(
N - i);
3203 for (
size_t i = 1; i <
N; ++i)
3204 ASSERT_LE(a(i - 1), a(i));
3207TEST(BucketSort, null_pointer_contract)
3209 EXPECT_THROW((bucket_sort<float>(
nullptr, 1)), std::invalid_argument);
3210 EXPECT_NO_THROW((bucket_sort<float>(
nullptr, 0)));
3213TEST(BucketSort, stability)
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;
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; };
3232 for (
size_t i = 1; i < n; ++i)
3233 ASSERT_LE(data[i - 1].group, data[i].group);
3237 EXPECT_EQ(data[0].seq, 0);
3238 EXPECT_EQ(data[1].seq, 2);
3240 EXPECT_EQ(data[2].seq, 3);
3241 EXPECT_EQ(data[3].seq, 5);
3243 EXPECT_EQ(data[4].seq, 1);
3244 EXPECT_EQ(data[5].seq, 4);
3248TEST(BucketSort, zero_buckets)
3250 int a[] = {3, 1, 2};
3252 const size_t num_buckets = 0;
3253 auto key = [](
const int &) ->
size_t {
return 0; };
3256 EXPECT_THROW(
bucket_sort(a, n, num_buckets, key), std::domain_error);
3263TEST(Timsort, already_sorted)
3265 constexpr size_t N = 200;
3268 for (
size_t i = 0; i <
N; ++i)
3269 a(i) =
static_cast<int>(i);
3272 for (
size_t i = 1; i <
N; ++i)
3273 ASSERT_LE(a(i - 1), a(i));
3276TEST(Timsort, reverse_sorted)
3278 constexpr size_t N = 200;
3281 for (
size_t i = 0; i <
N; ++i)
3282 a(i) =
static_cast<int>(
N - i);
3285 for (
size_t i = 1; i <
N; ++i)
3286 ASSERT_LE(a(i - 1), a(i));
3289TEST(Timsort, random_small)
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)));
3296TEST(Timsort, random_large)
3298 constexpr size_t N = 10000;
3301 std::mt19937 gen(42);
3302 std::uniform_int_distribution<int> dist(-1000000, 1000000);
3303 for (
size_t i = 0; i <
N; ++i)
3307 for (
size_t i = 1; i <
N; ++i)
3308 ASSERT_LE(a(i - 1), a(i));
3311TEST(Timsort, perf_large)
3313 if (not std::getenv(
"ENABLE_PERF_TESTS"))
3314 GTEST_SKIP() <<
"Skipping perf test (set ENABLE_PERF_TESTS to enable)";
3316 constexpr size_t N = 100000;
3319 std::mt19937 gen(42);
3320 std::uniform_int_distribution<int> dist(-1000000, 1000000);
3321 for (
size_t i = 0; i <
N; ++i)
3324 auto start = std::chrono::steady_clock::now();
3326 auto end = std::chrono::steady_clock::now();
3328 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
3331 if (
const char * env_ms = std::getenv(
"TIMSORT_MAX_MS"))
3332 max_ms = std::atol(env_ms);
3334 EXPECT_LE(duration, max_ms) <<
"Timsort performance regression detected";
3336 for (
size_t i = 1; i <
N; ++i)
3337 ASSERT_LE(a(i - 1), a(i));
3340TEST(Timsort, all_equal)
3342 constexpr size_t N = 100;
3345 for (
size_t i = 0; i <
N; ++i)
3349 for (
size_t i = 0; i <
N; ++i)
3350 EXPECT_EQ(a(i), 42);
3353TEST(Timsort, two_sorted_halves)
3355 constexpr size_t N = 200;
3359 for (
size_t i = 0; i <
N / 2; ++i)
3360 a(i) =
static_cast<int>(i * 2);
3362 for (
size_t i =
N / 2; i <
N; ++i)
3363 a(i) =
static_cast<int>((i -
N / 2) * 2 + 1);
3366 for (
size_t i = 1; i <
N; ++i)
3367 ASSERT_LE(a(i - 1), a(i));
3370TEST(Timsort, custom_comparator)
3372 constexpr size_t N = 50;
3375 std::mt19937 gen(99);
3376 for (
size_t i = 0; i <
N; ++i)
3377 a(i) =
static_cast<int>(gen() % 1000);
3380 for (
size_t i = 1; i <
N; ++i)
3381 ASSERT_GE(a(i - 1), a(i));
3384TEST(Timsort, dynarray_support)
3388 for (
size_t i = 1; i < a.
size(); ++i)
3389 ASSERT_LE(a(i - 1), a(i));
3392TEST(Timsort, array_support)
3395 for (
int x : {9, 1, 8, 2, 7, 3, 6, 4, 5, 0})
3399 for (
size_t i = 1; i < a.
size(); ++i)
3400 ASSERT_LE(a(i - 1), a(i));
3403TEST(Timsort, c_array_overload)
3405 int a[] = {5, 3, 8, 1, 9, 2, 7, 4, 6, 0};
3407 EXPECT_TRUE(std::is_sorted(std::begin(a), std::end(a)));
3410TEST(Timsort, dynlist_support)
3412 DynList<int> l = make_dynlist({5, 3, 8, 1, 9, 2, 7, 4, 6, 0});
3415 int prev = std::numeric_limits<int>::min();
3418 EXPECT_GE(it.get_curr(), prev);
3419 prev = it.get_curr();
3423TEST(Timsort, empty_and_singleton)
3427 EXPECT_EQ(d.
size(), 0u);
3432 ASSERT_EQ(a.
size(), 1u);
3436TEST(Timsort, null_pointer_contract)
3438 EXPECT_THROW((timsort<int>(
nullptr, 1)), std::invalid_argument);
3439 EXPECT_NO_THROW((timsort<int>(
nullptr, 0)));
3442TEST(Timsort, stability)
3452 {3, 0}, {1, 1}, {4, 2}, {1, 3}, {5, 4},
3453 {9, 5}, {2, 6}, {6, 7}, {5, 8}, {3, 9}
3455 const size_t n =
sizeof(data) /
sizeof(data[0]);
3457 auto cmp = [](
const Record & a,
const Record & b) {
return a.key < b.key; };
3461 for (
size_t i = 1; i < n; ++i)
3462 ASSERT_LE(data[i - 1].key, data[i].key);
3465 for (
size_t i = 1; i < n; ++i)
3466 if (data[i - 1].key == data[i].key)
3468 EXPECT_LT(data[i - 1].seq, data[i].seq)
3469 <<
"Stability violated at index " << i;
3473TEST(Timsort, string_sort)
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");
3491TEST(Timsort, nearly_sorted)
3493 constexpr size_t N = 500;
3496 for (
size_t i = 0; i <
N; ++i)
3497 a(i) =
static_cast<int>(i);
3500 std::mt19937 gen(12);
3501 for (
int k = 0;
k < 10; ++
k)
3503 size_t i = gen() %
N;
3504 size_t j = gen() %
N;
3505 std::swap(a(i), a(j));
3509 for (
size_t i = 1; i <
N; ++i)
3510 ASSERT_LE(a(i - 1), a(i));
3513TEST(Timsort, range_overload)
3515 int a[] = {9, 5, 3, 8, 1, 7, 2, 6, 4, 0};
3520 for (
int i = 3; i <= 7; ++i)
3521 ASSERT_LE(a[i - 1], a[i]);
3530TEST(Timsort, compute_minrun)
3543 for (
size_t n = 64; n < 10000; ++n)
3546 EXPECT_GE(mr, 32u) <<
"n=" << n;
3547 EXPECT_LE(mr, 64u) <<
"n=" << n;
static DynArray< int > make_dynarray(std::initializer_list< int > vals)
bool operator<(const Time &l, const Time &r)
static bool is_min_heap(const std::vector< int > &v)
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
static Array create_reserved(const size_t cap)
Build an empty array with room for at least cap items.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
constexpr bool is_empty() const noexcept
Checks if the container is empty.
static Array create(const size_t n)
Create an array with n logical elements.
T & append(const T &data)
Append a copy of data
Helper class to compare nodes of a linked list.
bool has_curr() const noexcept
Return true if the iterator has current item.
Doubly linked circular list node.
Iterator on a list of Dnode objects.
Node belonging to a double circular linked list with header node.
Dnode< T > * remove_first_ne() noexcept
Remove the first node and return its address.
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.
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.
Doubly-linked list (defined in tpl_dynList.H).
T & get_first()
Return the first item of the list.
T & append(const T &item)
T & get_last()
Return the last item of the list.
size_t size() const noexcept
Return the number of items of the list, in constant time.
bool has_curr() const noexcept
Single linked list of nodes.
constexpr bool is_empty() const noexcept
Number Theoretic Transform over Z / MOD Z.
Comparator wrapper that inverts the comparison order.
Link of a single linked list non-circular and without header node.
constexpr bool is_empty() const noexcept
Return true if this is empty.
Slinknc * remove_next() noexcept
void insert(Slinknc *p) noexcept
insert(p) inserts the node pointed by p after this.
Minimal std::expected-style result type for C++20.
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
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.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
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.
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.
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.
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.
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.
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().
Comparator specialization for Dnode objects.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
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.