TestInsertionSort.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2022, Marc Luqué <marc.luque@outlook.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibTest/TestCase.h>
  7. #include <AK/InsertionSort.h>
  8. #include <AK/Random.h>
  9. #include <AK/Vector.h>
  10. static constexpr int const n = 10;
  11. static constexpr int const iterations = 10;
  12. static constexpr int const seed = 1337;
  13. TEST_CASE(sorts_ascending)
  14. {
  15. srand(seed);
  16. for (int i = 0; i < iterations; ++i) {
  17. Vector<int, n> ints;
  18. for (int j = 0; j < n; ++j)
  19. ints.append(get_random<int>());
  20. Vector<int, n> ints_copy = ints;
  21. insertion_sort(ints);
  22. insertion_sort(ints_copy);
  23. for (int j = 0; j < n - 1; ++j) {
  24. EXPECT(ints[j] <= ints[j + 1]);
  25. EXPECT_EQ(ints[j], ints_copy[j]);
  26. EXPECT_EQ(ints[j + 1], ints_copy[j + 1]);
  27. }
  28. }
  29. }
  30. TEST_CASE(sorts_decending)
  31. {
  32. srand(seed);
  33. for (int i = 0; i < iterations; ++i) {
  34. Vector<int, n> ints;
  35. for (int j = 0; j < n; ++j)
  36. ints.append(get_random<int>());
  37. Vector<int, n> ints_copy = ints;
  38. insertion_sort(ints, [](auto& a, auto& b) { return a > b; });
  39. insertion_sort(ints_copy, [](auto& a, auto& b) { return a > b; });
  40. for (int j = 0; j < n - 1; ++j) {
  41. EXPECT(ints[j] >= ints[j + 1]);
  42. EXPECT_EQ(ints[j], ints_copy[j]);
  43. EXPECT_EQ(ints[j + 1], ints_copy[j + 1]);
  44. }
  45. }
  46. }
  47. TEST_CASE(sorts_subrange_without_affecting_outside_elements)
  48. {
  49. Vector<int> ints = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
  50. Vector<int> const original_ints = ints;
  51. ssize_t const start = 3;
  52. ssize_t const end = 6;
  53. insertion_sort(ints, start, end, [](auto& a, auto& b) { return a < b; });
  54. for (ssize_t i = start; i < end; ++i) {
  55. EXPECT(ints[i] <= ints[i + 1]);
  56. }
  57. for (ssize_t i = 0; i < start; ++i) {
  58. EXPECT_EQ(ints[i], original_ints[i]);
  59. }
  60. for (ssize_t i = end + 1; i < static_cast<ssize_t>(ints.size()); ++i) {
  61. EXPECT_EQ(ints[i], original_ints[i]);
  62. }
  63. }