The subsequent routines are sorting arrays. Static linked lists are also applicable to the sorting of linked lists. For the sake of simplicity, only the single key code is sorted, and the final results are sorted from start to end in ascending order. The following is a unified test procedure:
# Include <iostream>
# Include <iomanip>
Using namespace STD;
# Include <stdlib. h>
# Include <time. h>
# Include <math. h>
# Include "insertsort. H"
# Define random (Num) (RAND () % (Num ))
# Define randomize () srand (unsigned) Time (null ))
# Define n 10000 // Number of sorting Elements
# Define sort insertsort // sorting method
Class timer // unit: Ms
{
Public:
Void start () {start_t = clock ();}
Clock_t time () {return (clock ()-start_t );}
PRIVATE:
Clock_t start_t;
};
Int kcn, rmn; timer;
Void test (int A [])
{
Timer. Start ();
Sort <int> (A, N, kcn, rmn );
Cout <"/ttimespared:" <timer. Time () <"Ms" <Endl;
Cout <"kcn =" <left <SETW (11) <kcn;
Cout <"kcn/N =" <left <SETW (11) <(double) kcn/N;
Cout <"kcn/n ^ 2 =" <left <SETW (11) <(double) kcn/n;
Cout <"kcn/nlogn =" <left <SETW (11) <(double) kcn/n/log (double) n) * log (2.0) <Endl;
Cout <"rmn =" <left <SETW (11) <rmn;
Cout <"rmn/N =" <left <SETW (11) <(double) rmn/N;
Cout <"rmn/n ^ 2 =" <left <SETW (11) <(double) rmn/n;
Cout <"rmn/nlogn =" <left <SETW (11) <(double) rmn/n/log (double) n) * log (2.0) <Endl;
}
Int main ()
{
Int I;
// Randomize (); this sentence is not added to compare different sorting algorithms under the same circumstances.
Int * ascending = new int [N]; // ascending sequence
Int * descending = new int [N]; // descending sequence
Int * randomness = new int [N]; // random sequence
For (I = 0; I <n; I ++) {ascending [I] = I; randomness [I] = I; descending [I] = n-I-1 ;}
For (I = 0; I <n; I ++) Swap (randomness [I], randomness [random (n)]);
Cout <"Sort Ascending n =" <n; test (ascending );
Cout <"Sort randomness n =" <n; test (randomness );
Cout <"Sort Descending n =" <n; test (descending );
Return 0;
}
Note that kcn and rmn are not required by the algorithm, this is to provide an intuitive evaluation of the algorithm's performance (without the calculation of those formulas ). Sorting 10000 integers should be the most efficient test method. We recommend that you do not increase the number of records. First, you do not have to wait too long in the worst case, the second is to avoid overflow of kcn and rmn. In addition, some recursive algorithms may overflow when the number of records is too large, resulting in program crash.