I have introduced common sorting algorithms before. You can view them here.
The previously implemented code is for int-type algorithms. Now I have rewritten the code into a template, which can be applied to some common types.
Two timing methods are used to test and compare different sorting algorithms. Note that in the following two sections of code, void (* _ sort []) (T *, INT) is a function pointer array.
1. Use the clock function to count the number of clocks used by the sorting algorithm.
The Code is as follows:
Template <class T>
Void clock_test ()
{
Void (* _ sort []) (T *, INT) = {insert_sort, binary_insert_sort, shell_sort, shell_sort2, select_sort,
Select_sort2, select_sort3, heap_sort, bubble_sort, bubble_sort2, quick_sort,
Merge_sort, merge_sort2, merge_sort3, merge_sort4, rank_sort, rank_sort2 };
Int Len = sizeof (_ sort)/sizeof (_ sort [0]);
Clock_t start, finish;
// Cout <clocks_per_sec <Endl;
Cout <"Memory has been attached successfully \ t memory has been attached too many \ t memory has been released too many \ t" <Endl;
Int step = 100;
For (int K = 100; k <= 100000; k + = step)
{
Const int n = K;
T arr [N];
Double TM [N];
// Srand (time (0 ));
For (INT I = 0; I <n; I ++)
Arr [I] = rand () %1000;
For (INT I = 0; I <Len; I ++ ){
Start = clock ();
_ Sort [I] (ARR, N );
Finish = clock ();
TM [I] = (finish-Start) * 1.0/clocks_per_sec;
}
Cout <k <'\ T ';
For (INT I = 0; I <Len; I ++)
Cout <TM [I] <'\ T ';
Cout <Endl;
}
}
Some test outputs are as follows: