TestQsort.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2020, Sahan Fernando <sahan.h.fernando@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibTest/TestCase.h>
  7. #include <AK/QuickSort.h>
  8. #include <AK/Random.h>
  9. #include <AK/String.h>
  10. #include <AK/Vector.h>
  11. #include <stdlib.h>
  12. const size_t NUM_RUNS = 10;
  13. struct SortableObject {
  14. int m_key;
  15. int m_payload;
  16. };
  17. static int compare_sortable_object(const void* a, const void* b)
  18. {
  19. const int key1 = static_cast<const SortableObject*>(a)->m_key;
  20. const int key2 = static_cast<const SortableObject*>(b)->m_key;
  21. if (key1 < key2) {
  22. return -1;
  23. } else if (key1 == key2) {
  24. return 0;
  25. } else {
  26. return 1;
  27. }
  28. }
  29. static int calc_payload_for_pos(size_t pos)
  30. {
  31. pos *= 231;
  32. return pos ^ (pos << 8) ^ (pos << 16) ^ (pos << 24);
  33. }
  34. static void shuffle_vec(Vector<SortableObject>& test_objects)
  35. {
  36. for (size_t i = 0; i < test_objects.size() * 3; ++i) {
  37. auto i1 = get_random_uniform(test_objects.size());
  38. auto i2 = get_random_uniform(test_objects.size());
  39. swap(test_objects[i1], test_objects[i2]);
  40. }
  41. }
  42. TEST_CASE(quick_sort)
  43. {
  44. // Generate vector of SortableObjects in sorted order, with payloads determined by their sorted positions
  45. Vector<SortableObject> test_objects;
  46. for (auto i = 0; i < 1024; ++i) {
  47. test_objects.append({ i * 137, calc_payload_for_pos(i) });
  48. }
  49. for (size_t i = 0; i < NUM_RUNS; i++) {
  50. // Shuffle the vector, then sort it again
  51. shuffle_vec(test_objects);
  52. qsort(test_objects.data(), test_objects.size(), sizeof(SortableObject), compare_sortable_object);
  53. // Check that the objects are sorted by key
  54. for (auto i = 0u; i + 1 < test_objects.size(); ++i) {
  55. const auto& key1 = test_objects[i].m_key;
  56. const auto& key2 = test_objects[i + 1].m_key;
  57. if (key1 > key2) {
  58. FAIL(String::formatted("saw key {} before key {}\n", key1, key2));
  59. }
  60. }
  61. // Check that the object's payloads have not been corrupted
  62. for (auto i = 0u; i < test_objects.size(); ++i) {
  63. const auto expected = calc_payload_for_pos(i);
  64. const auto payload = test_objects[i].m_payload;
  65. if (payload != expected) {
  66. FAIL(String::formatted("Expected payload {} for pos {}, got payload {}", expected, i, payload));
  67. }
  68. }
  69. }
  70. }