MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / main

Function main

Exercises/Modules/Chapter 19/Soln19_03/Soln19_03.cpp:46–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

44}
45
46int main()
47{
48 unsigned count {};
49 const auto counting_less{ [&count](int x, int y) { ++count; return x < y; } };
50
51 for (auto size : { 500u, 1'000u, 2'000u, 4'000u })
52 {
53 const auto numbers{ generateRandomNumbers(size) };
54
55 count = 0; // Reset the count
56 auto copy{ numbers }; // Ensure both sorrting algorithms work on exact same random sequence
57 quicksort(copy, counting_less);
58 const auto quicksort_count{ count };
59
60 count = 0; // Repeat for bubble sort algorithm
61 copy = numbers;
62 bubbleSort(copy, counting_less);
63 const auto bubble_sort_count{ count };
64
65 // Not requested, but it is interesting (see earlier)
66 // to also compare with the sorting algorithm of the C++ Standard Library
67 count = 0; // Repeat once more for std::ranges::sort() (see Chapter 20)
68 copy = numbers;
69 std::ranges::sort(copy, counting_less);
70 const auto std_sort_count{ count };
71
72 const auto quick_sort_theory = static_cast<unsigned>(size * std::log2(size));
73 const auto bubble_sort_theory = size * size;
74 const auto std_sort_theory = static_cast<unsigned>(size * std::log2(size));
75
76 std::cout
77 << std::format(
78 "Number of comparisons for {} elements:\n"
79 " - quicksort: {} (n*log(n): {}; ratio: {:.2})\n"
80 " - bubble sort: {} (n*n: {}; ratio: {:.2})\n"
81 " - Standard Library sort: {} (n*log(n): {}; ratio: {:.2})\n",
82 size,
83 quicksort_count, quick_sort_theory, static_cast<float>(quick_sort_theory) / quicksort_count,
84 bubble_sort_count, bubble_sort_theory, static_cast<float>(bubble_sort_theory) / bubble_sort_count,
85 std_sort_count, std_sort_theory, static_cast<float>(std_sort_theory) / std_sort_count
86 )
87 << std::endl;
88 }
89}

Callers

nothing calls this directly

Calls 4

bubbleSortFunction · 0.85
generateRandomNumbersFunction · 0.70
quicksortFunction · 0.50
sortFunction · 0.50

Tested by

no test coverage detected