Scenario: 1. sometimes it is necessary to sort the data in the set or array and then display it. 2. because some data structure processing needs to sort the array before it can be performed. file: test_sort.cpp [cpp] # include <stdio. h> # include <algorithm> # include <stdlib. h> # include <iostream> # include <time. h> # include <assert. h> # include <vector> # include <windows. h> using namespace std; void InsertSort (vector <int> & array, size_t length) {int key = 0; for (size_t j = 1; j <length; ++ j) {int I = J-1; key = array [j]; while (I> = 0 & array [I]> key) {array [I + 1] = array [I]; -- I;} array [I + 1] = key;} bool cmp (int a, int B) {return a <B;} int main (int argc, char * argv []) {printf ("Hello, world \ n "); // RAND_MAX srand (time (NULL); const int kMaxNum = 100000; vector <int> v1 (kMaxNum, 0); for (int I = 0; I <kMaxNum; ++ I) {v1 [I] = rand () % 100;} vector <int> v2 (v1); // this parameter is millisecond-level in windows. // 1. sort by library function. cout <CLOCKS_PER_SEC <endl; double time = clock (); sort (v1.begin (), v1.end (), cmp); double Inteval = clock ()-time; cout <"sorting time unit (MS):" <Inteval <endl; // 1. verify the sorting. int pre = v1 [0]; for (int I = 0; I <kMaxNum; ++ I) {assert (v1 [I]> = pre ); pre = v1 [I];} // 2. use your own sorting algorithm. size_t length = v2.size (); time = clock (); InsertSort (v2, length); Inteval = clock ()-time; cout <"insertion sorting time unit (MS ): "<Inteval <endl; pre = v1 [0]; for (int I = 0; I <kMaxNum; ++ I) {assert (v1 [I]> = pre); pre = v1 [I];} return 0;} output, executed four times. It can be seen that insertion sorting is indeed not very good: [plain] Hello, world 1000 sorting time unit (MS): 36 insert sorting time unit (MS): 32114 Hello, world 1000 sorting time unit (MS ): 38 insertion sorting time unit (MS): 27737 Hello, world 1000 sorting time unit (MS): 37 insertion sorting time unit (MS): 32807 Hello, world 1000 sorting time unit (MS): 44 insert sorting time unit (MS): 28157