Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
sort_benchmark.C
Go to the documentation of this file.
1
180#include <iostream>
181#include <iomanip>
182#include <chrono>
183#include <string>
184#include <functional>
185#include <random>
186
187#include <tclap/CmdLine.h>
188
189#include <tpl_dynArray.H>
190#include <tpl_array.H>
191#include <tpl_dynDlist.H>
192#include <htlist.H>
193#include <tpl_sort_utils.H>
194#include <ahSort.H>
195
196using namespace std;
197using namespace Aleph;
198using namespace std::chrono;
199
200// =============================================================================
201// Configuration
202// =============================================================================
203
205{
206 size_t num_elements = 10000;
207 bool run_slow_algorithms = false; // O(n²) algorithms
208 bool test_arrays = true;
209 bool test_lists = true;
210 bool verbose = false;
211 unsigned seed = 42;
212};
213
214// =============================================================================
215// Timer utility
216// =============================================================================
217
218class Timer
219{
220 high_resolution_clock::time_point start_time;
221 high_resolution_clock::time_point stop_time;
222 bool stopped = false;
223
224public:
225 void start()
226 {
227 start_time = high_resolution_clock::now();
228 stopped = false;
229 }
230
231 // Freezes the time that elapsed_ms() reports, so that the check of the
232 // result of a sort does not count in it
233 void stop()
234 {
235 stop_time = high_resolution_clock::now();
236 stopped = true;
237 }
238
239 double elapsed_ms() const
240 {
241 const auto end_time = stopped ? stop_time : high_resolution_clock::now();
242 return duration<double, milli>(end_time - start_time).count();
243 }
244};
245
246// =============================================================================
247// Data generators
248// =============================================================================
249
251{
252 mt19937 rng;
253
254public:
255 explicit DataGenerator(unsigned seed) : rng(seed) {}
256
258 void random(DynArray<int>& arr, size_t n)
259 {
260 arr.empty();
261 uniform_int_distribution<int> dist(1, static_cast<int>(n * 10));
262 for (size_t i = 0; i < n; ++i)
263 arr.append(dist(rng));
264 }
265
267 void sorted_asc(DynArray<int>& arr, size_t n)
268 {
269 arr.empty();
270 for (size_t i = 0; i < n; ++i)
271 arr.append(static_cast<int>(i));
272 }
273
275 void sorted_desc(DynArray<int>& arr, size_t n)
276 {
277 arr.empty();
278 for (size_t i = n; i > 0; --i)
279 arr.append(static_cast<int>(i));
280 }
281
283 void nearly_sorted(DynArray<int>& arr, size_t n)
284 {
285 sorted_asc(arr, n);
286 size_t swaps = n / 20; // 5%
287 uniform_int_distribution<size_t> dist(0, n - 1);
288 for (size_t i = 0; i < swaps; ++i)
289 {
290 size_t a = dist(rng);
291 size_t b = dist(rng);
292 swap(arr(a), arr(b));
293 }
294 }
295
297 void few_unique(DynArray<int>& arr, size_t n)
298 {
299 arr.empty();
300 uniform_int_distribution<int> dist(1, 10);
301 for (size_t i = 0; i < n; ++i)
302 arr.append(dist(rng));
303 }
304
306 void sawtooth(DynArray<int>& arr, size_t n)
307 {
308 arr.empty();
309 size_t run_size = max(n / 10, size_t(1));
310 for (size_t i = 0; i < n; ++i)
311 arr.append(static_cast<int>(i % run_size));
312 }
313};
314
315// =============================================================================
316// Container converters
317// =============================================================================
318
319template <typename T>
320void to_dynlist(const DynArray<T>& arr, DynList<T>& list)
321{
322 list.empty();
323 for (size_t i = 0; i < arr.size(); ++i)
324 list.append(arr(i));
325}
326
327template <typename T>
328void to_dyndlist(const DynArray<T>& arr, DynDlist<T>& list)
329{
330 list.empty();
331 for (size_t i = 0; i < arr.size(); ++i)
332 list.append(arr(i));
333}
334
335template <typename T>
336void to_array(const DynArray<T>& src, Array<T>& dst)
337{
338 dst.empty();
339 for (size_t i = 0; i < src.size(); ++i)
340 dst.append(src(i));
341}
342
343// =============================================================================
344// Output formatting
345// =============================================================================
346
348{
349 cout << "\n" << string(79, '=') << "\n";
350 cout << setw(18) << left << "Algorithm"
351 << setw(15) << left << "Distribution"
352 << setw(12) << left << "Container"
353 << setw(14) << right << "Time (ms)"
354 << setw(10) << "Status"
355 << endl;
356 cout << string(79, '-') << endl;
357}
358
359void print_result(const string& algo, const string& dist,
360 const string& container, double time_ms, bool ok)
361{
362 cout << setw(18) << left << algo
363 << setw(15) << left << dist
364 << setw(12) << left << container
365 << setw(14) << right << fixed << setprecision(2) << time_ms
366 << setw(10) << (ok ? "OK" : "FAIL")
367 << endl;
368}
369
371{
372 cout << string(79, '-') << endl;
373}
374
375// =============================================================================
376// Array sorting benchmarks
377// =============================================================================
378
380 const string& dist_name,
381 const DynArray<int>& source_data)
382{
383 Timer timer;
384 DynArray<int> arr;
385
386 // Note: DynArray uses segmented blocks (not contiguous memory)
387 // So we must use Aleph's sorting functions, not std::sort
388
389 // Introsort (hybrid: quicksort + heapsort fallback) - RECOMMENDED
390 arr = source_data;
391 timer.start();
392 introsort(arr);
393 timer.stop();
394 print_result("Introsort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
395
396 // Quicksort (optimized iterative version) - uses DynArray::operator()
397 arr = source_data;
398 timer.start();
399 quicksort_op(arr);
400 timer.stop();
401 print_result("Quicksort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
402
403 // Heapsort - uses DynArray::operator()
404 arr = source_data;
405 timer.start();
406 heapsort(arr);
407 timer.stop();
408 print_result("Heapsort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
409
410 // Shell Sort - uses DynArray::operator()
411 arr = source_data;
412 timer.start();
413 shellsort(arr);
414 timer.stop();
415 print_result("Shell Sort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
416
417 // O(n²) algorithms - only for small inputs
418 if (config.run_slow_algorithms and config.num_elements <= 30000)
419 {
420 arr = source_data;
421 timer.start();
422 insertion_sort(arr);
423 timer.stop();
424 print_result("Insertion Sort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
425
426 arr = source_data;
427 timer.start();
428 selection_sort(arr);
429 timer.stop();
430 print_result("Selection Sort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
431
432 if (config.num_elements <= 10000)
433 {
434 arr = source_data;
435 timer.start();
436 bubble_sort(arr);
437 timer.stop();
438 print_result("Bubble Sort", dist_name, "DynArray", timer.elapsed_ms(), is_sorted(arr));
439 }
440 }
441}
442
443// =============================================================================
444// Contiguous Array benchmarks (Array<T>)
445// =============================================================================
446
448 const string& dist_name,
449 const DynArray<int>& source_data)
450{
451 (void)config; // Currently unused
452 Timer timer;
453 Array<int> arr;
454
455 // Array<T> uses contiguous memory - faster than DynArray's segmented blocks
456 // Introsort with STL-style pointer interface achieves best cache locality
457
458 // Introsort on Array<T> - using container interface
459 to_array(source_data, arr);
460 timer.start();
461 introsort(arr);
462 timer.stop();
463 print_result("Introsort", dist_name, "Array", timer.elapsed_ms(), is_sorted(arr));
464
465 // Introsort with STL-style pointer interface (begin/end)
466 to_array(source_data, arr);
467 timer.start();
468 introsort(&arr(0), &arr(0) + arr.size());
469 timer.stop();
470 print_result("Intro(ptr)", dist_name, "Array", timer.elapsed_ms(), is_sorted(arr));
471
472 // Heapsort on Array<T> - contiguous memory allows optimal heap operations
473 to_array(source_data, arr);
474 timer.start();
475 faster_heapsort(&arr(0), arr.size());
476 timer.stop();
477 print_result("Heapsort", dist_name, "Array", timer.elapsed_ms(), is_sorted(arr));
478}
479
480// =============================================================================
481// List sorting benchmarks
482// =============================================================================
483
485 const string& dist_name,
486 const DynArray<int>& source_data)
487{
488 Timer timer;
489 DynList<int> slist;
490 DynDlist<int> dlist;
491
492 // DynList - Merge Sort
493 to_dynlist(source_data, slist);
494 timer.start();
495 mergesort(slist);
496 timer.stop();
497 print_result("Merge Sort", dist_name, "DynList", timer.elapsed_ms(), is_sorted(slist));
498
499 // DynList - Quicksort
500 to_dynlist(source_data, slist);
501 timer.start();
502 quicksort(slist);
503 timer.stop();
504 print_result("Quicksort", dist_name, "DynList", timer.elapsed_ms(), is_sorted(slist));
505
506 // DynDlist - Merge Sort
507 to_dyndlist(source_data, dlist);
508 timer.start();
509 mergesort(dlist);
510 timer.stop();
511 print_result("Merge Sort", dist_name, "DynDlist", timer.elapsed_ms(), is_sorted(dlist));
512
513 // DynDlist - Quicksort
514 to_dyndlist(source_data, dlist);
515 timer.start();
516 quicksort(dlist);
517 timer.stop();
518 print_result("Quicksort", dist_name, "DynDlist", timer.elapsed_ms(), is_sorted(dlist));
519
520 // O(n²) - only for small inputs
521 if (config.run_slow_algorithms and config.num_elements <= 10000)
522 {
523 to_dynlist(source_data, slist);
524 timer.start();
525 insertion_sort(slist);
526 timer.stop();
527 print_result("Insertion Sort", dist_name, "DynList", timer.elapsed_ms(), is_sorted(slist));
528
529 to_dyndlist(source_data, dlist);
530 timer.start();
531 in_place_sort(dlist);
532 timer.stop();
533 print_result("Insertion Sort", dist_name, "DynDlist", timer.elapsed_ms(), is_sorted(dlist));
534 }
535}
536
537// =============================================================================
538// Main benchmark runner
539// =============================================================================
540
542{
543 cout << "\n";
544 cout << "============================================================\n";
545 cout << " ALEPH-W SORTING ALGORITHMS BENCHMARK\n";
546 cout << "============================================================\n";
547 cout << "\nConfiguration:\n";
548 cout << " Elements: " << config.num_elements << "\n";
549 cout << " O(n^2) algos: " << (config.run_slow_algorithms ? "Yes" : "No") << "\n";
550 cout << " Test arrays: " << (config.test_arrays ? "Yes" : "No") << "\n";
551 cout << " Test lists: " << (config.test_lists ? "Yes" : "No") << "\n";
552 cout << " Random seed: " << config.seed << "\n";
553
554 DataGenerator gen(config.seed);
555 DynArray<int> data;
556
557 // Distribution names and generators
558 struct DistInfo
559 {
560 const char* name;
561 void (DataGenerator::*generator)(DynArray<int>&, size_t);
562 };
563
564 DistInfo distributions[] = {
565 {"Random", &DataGenerator::random},
566 {"Sorted", &DataGenerator::sorted_asc},
567 {"Reverse", &DataGenerator::sorted_desc},
568 {"Nearly Sorted", &DataGenerator::nearly_sorted},
569 {"Few Unique", &DataGenerator::few_unique},
570 {"Sawtooth", &DataGenerator::sawtooth}
571 };
572
573 print_header();
574
575 for (const auto& dist : distributions)
576 {
577 // Generate data for this distribution
578 (gen.*(dist.generator))(data, config.num_elements);
579
580 if (config.test_arrays)
581 {
582 benchmark_array_algorithms(config, dist.name, data);
583 benchmark_contiguous_array(config, dist.name, data);
584 }
585
586 if (config.test_lists)
587 benchmark_list_algorithms(config, dist.name, data);
588
590 }
591
592 cout << "\nBenchmark completed successfully!\n\n";
593}
594
595// =============================================================================
596// Complexity demonstration
597// =============================================================================
598
600{
601 cout << "\n";
602 cout << "============================================================\n";
603 cout << " COMPLEXITY DEMONSTRATION\n";
604 cout << "============================================================\n";
605 cout << "\nShows how sorting time scales with input size.\n";
606 cout << "For O(n log n): doubling n roughly doubles time.\n";
607 cout << "For O(n^2): doubling n roughly quadruples time.\n\n";
608
609 DataGenerator gen(base_config.seed);
610 DynArray<int> data;
611 DynArray<int> arr;
612 Array<int> carr; // Contiguous array
613 DynList<int> list;
614 Timer timer;
615
616 size_t sizes[] = {1000, 2000, 4000, 8000, 16000, 32000};
617
618 cout << setw(10) << "Size"
619 << setw(15) << "Introsort"
620 << setw(15) << "Intro(Array)"
621 << setw(15) << "Quicksort"
622 << setw(15) << "Merge (list)"
623 << endl;
624 cout << string(70, '-') << endl;
625
626 for (size_t n : sizes)
627 {
628 gen.random(data, n);
629 cout << setw(10) << n;
630
631 // Introsort (DynArray) - hybrid with O(n log n) guaranteed
632 arr = data;
633 timer.start();
634 introsort(arr);
635 cout << setw(15) << fixed << setprecision(2) << timer.elapsed_ms();
636
637 // Introsort (Array<T> - contiguous memory)
638 to_array(data, carr);
639 timer.start();
640 introsort(carr);
641 cout << setw(15) << timer.elapsed_ms();
642
643 // Quicksort (DynArray)
644 arr = data;
645 timer.start();
646 quicksort_op(arr);
647 cout << setw(15) << timer.elapsed_ms();
648
649 // Merge Sort (DynList)
650 to_dynlist(data, list);
651 timer.start();
652 mergesort(list);
653 cout << setw(15) << timer.elapsed_ms();
654
655 cout << endl;
656 }
657
658 cout << "\nIntrosort = quicksort + heapsort fallback + insertion sort for small.\n";
659 cout << "Array uses contiguous memory, DynArray uses segmented blocks.\n";
660}
661
662// =============================================================================
663// Algorithm selection guide
664// =============================================================================
665
667{
668 cout << "\n";
669 cout << "============================================================\n";
670 cout << " ALGORITHM SELECTION GUIDE\n";
671 cout << "============================================================\n";
672 cout << R"(
673+-------------------+------------------------+-------------------------+
674| Scenario | Best Choice | Why |
675+-------------------+------------------------+-------------------------+
676| General purpose | introsort() | Fast + O(n log n) guarantee |
677| Nearly sorted | insertion_sort() | O(n) for sorted data |
678| Guaranteed O(nlogn)| introsort()/heapsort()| No worst case O(n^2) |
679| Linked lists | mergesort() | O(1) extra space |
680| Stability needed | mergesort() | Preserves equal order |
681| Limited memory | heapsort() | O(1) extra space |
682| Small arrays (<50)| insertion_sort() | Low overhead |
683| External sorting | mergesort() | Sequential access |
684| Medium arrays | shellsort() | Good balance |
685| Adversarial data | introsort() | Immune to quicksort killers |
686+-------------------+------------------------+-------------------------+
687
688For Aleph-w containers:
689 - DynArray: Use introsort() (recommended), quicksort_op(), or heapsort()
690 - DynList: Use mergesort() (O(1) extra space for lists!)
691 - DynDlist: Use mergesort() or quicksort()
692
693Note: introsort() = quicksort + heapsort fallback + insertion sort for small
694 partitions. Same speed as quicksort but with O(n log n) guarantee.
695)";
696}
697
698// =============================================================================
699// Main
700// =============================================================================
701
702int main(int argc, char* argv[])
703{
704 try
705 {
706 TCLAP::CmdLine cmd(
707 "Comprehensive sorting algorithm benchmark for Aleph-w.\n"
708 "Tests multiple algorithms across different data distributions "
709 "and container types.",
710 ' ', "1.0"
711 );
712
713 TCLAP::ValueArg<size_t> nArg(
714 "n", "count",
715 "Number of elements to sort",
716 false, 10000, "count", cmd
717 );
718
719 TCLAP::SwitchArg allArg(
720 "a", "all",
721 "Include O(n^2) algorithms (selection, insertion, bubble)",
722 cmd, false
723 );
724
725 TCLAP::SwitchArg arrayOnlyArg(
726 "", "array-only",
727 "Only test array-based containers",
728 cmd, false
729 );
730
731 TCLAP::SwitchArg listOnlyArg(
732 "", "list-only",
733 "Only test linked list containers",
734 cmd, false
735 );
736
737 TCLAP::SwitchArg complexityArg(
738 "c", "complexity",
739 "Run complexity demonstration (time vs size)",
740 cmd, false
741 );
742
743 TCLAP::SwitchArg guideArg(
744 "g", "guide",
745 "Print algorithm selection guide",
746 cmd, false
747 );
748
749 TCLAP::ValueArg<unsigned> seedArg(
750 "s", "seed",
751 "Random seed for reproducible results",
752 false, 42, "seed", cmd
753 );
754
755 TCLAP::SwitchArg verboseArg(
756 "v", "verbose",
757 "Verbose output",
758 cmd, false
759 );
760
761 cmd.parse(argc, argv);
762
763 BenchmarkConfig config;
764 config.num_elements = nArg.getValue();
765 config.run_slow_algorithms = allArg.getValue();
766 config.test_arrays = not listOnlyArg.getValue();
767 config.test_lists = not arrayOnlyArg.getValue();
768 config.seed = seedArg.getValue();
769 config.verbose = verboseArg.getValue();
770
771 if (listOnlyArg.getValue() and arrayOnlyArg.getValue())
772 {
773 cerr << "Error: Cannot specify both --array-only and --list-only\n";
774 return 1;
775 }
776
777 if (guideArg.getValue())
778 {
780 return 0;
781 }
782
783 if (complexityArg.getValue())
784 {
786 return 0;
787 }
788
789 run_benchmarks(config);
790
791 return 0;
792 }
793 catch (TCLAP::ArgException& e)
794 {
795 cerr << "Error: " << e.error() << " for argument " << e.argId() << endl;
796 return 1;
797 }
798 catch (exception& e)
799 {
800 cerr << "Error: " << e.what() << endl;
801 return 1;
802 }
803}
High-level sorting functions for Aleph containers.
int main()
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
size_t size() const noexcept
Return the current dimension of array.
T & append()
Allocate a new entry to the end of array.
void empty() noexcept
Empty the array.
Dynamic doubly linked list with O(1) size and bidirectional access.
T & append(const T &item)
Append a copied item at the end of the list.
void empty() noexcept
@brief Empties the container.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
void empty() noexcept
empty the list
Definition htlist.H:1576
void nearly_sorted(DynArray< int > &arr, size_t n)
Nearly sorted: 5% of elements are swapped.
void sawtooth(DynArray< int > &arr, size_t n)
Sawtooth pattern: multiple ascending runs.
void sorted_desc(DynArray< int > &arr, size_t n)
Sorted in descending order.
DataGenerator(unsigned seed)
void random(DynArray< int > &arr, size_t n)
Uniformly distributed random integers.
void sorted_asc(DynArray< int > &arr, size_t n)
Already sorted in ascending order.
void few_unique(DynArray< int > &arr, size_t n)
Few unique values (high repetition)
high_resolution_clock::time_point stop_time
void start()
bool stopped
void stop()
double elapsed_ms() const
chrono::high_resolution_clock::time_point start
high_resolution_clock::time_point start_time
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
Array< typename C::Item_Type > to_array(const C &c)
Convenience wrapper identical to to_Array (copy contents).
Definition ah-convert.H:181
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.
bool is_sorted(const Container< T > &cont, const Compare &cmp=Compare())
Check if a container is sorted in ascending order.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
DynArray< T > & in_place_sort(DynArray< T > &c, Cmp cmp=Cmp())
Sorts a DynArray in place.
Definition ahSort.H:328
and
Check uniqueness with explicit hash + equality functors.
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 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.
constexpr void faster_heapsort(T *array, const size_t n, const Compare &cmp=Compare())
Optimized version of heapsort.
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).
void quicksort_op(C< T > &a, const Compare &cmp=Compare(), const size_t threshold=Quicksort_Threshold)
Optimized quicksort for containers using operator().
STL namespace.
void to_dynlist(const DynArray< T > &arr, DynList< T > &list)
void run_benchmarks(const BenchmarkConfig &config)
void benchmark_contiguous_array(const BenchmarkConfig &config, const string &dist_name, const DynArray< int > &source_data)
void to_dyndlist(const DynArray< T > &arr, DynDlist< T > &list)
void benchmark_array_algorithms(const BenchmarkConfig &config, const string &dist_name, const DynArray< int > &source_data)
void demonstrate_complexity(const BenchmarkConfig &base_config)
void print_result(const string &algo, const string &dist, const string &container, double time_ms, bool ok)
void benchmark_list_algorithms(const BenchmarkConfig &config, const string &dist_name, const DynArray< int > &source_data)
void print_recommendations()
void print_header()
void print_separator()
CmdLine cmd
Definition testHash.C:48
ValueArg< size_t > seed
Definition testHash.C:53
Dynamic array container with automatic resizing.
Lazy and scalable dynamic array implementation.
Dynamic doubly linked list implementation.
Comprehensive sorting algorithms and search utilities for Aleph-w.