We all knowC ++ sortingThere are four common methods: insert sorting, Hill sorting, exchange sorting, and select sorting. This article introducesInsert sort. Before introducing insertion, introduce the test programs in our entire series of articles.
Test procedure
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
- # Include
- Using NamespaceStd;
- # Include
- # Include
- # Include
- # 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
- ClassTimer// Unit: ms
- {
- Public:
- VoidStart () {start_t = clock ();}
- Clock_tTime (){Return(Clock ()-start_t );}
- Private:
- Clock_tStart_t;
- };
- IntKCN, RMN; timer TIMER;
- VoidTest (IntA [])
- {
- 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;
- }
- IntMain ()
- {
- IntI;
- // 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 );
- Return0;
- }
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.