A simple example

int i, sum = 0; # Execute 1 times int n = 100; # Execute 1 times for ( i = 0; i < n; i++ ) { # Executed n+1 times sum += i; # Loop executed n times } // Algorithm execution times = 1 + 1 + (n + 1) + (n + 1) = 2n + 4

2. Derivation of large O-order method

1. Replace all the addition constants in the running time with constant 1.

2. Only the highest order term is reserved in the modified run times function.

3. If the highest order exists and is not 1, remove the constant multiplied by this term.

III. example of constant order O(1)

int i,sum = 0; # Execute 1 times int n = 100; # Execute 1 times sum = (1+n)*n/2; # Execute 1 times printf("%d", sum); # Execute 1 times // Total execution times: 4, but due to addition, the time complexity is recorded as O(1)

IV. example of linear order O(n)

int i; for (i = 0; i < n; i++ ) { /* Calculation sequence with O(1) time complexity */ } // Because the code of the loop body needs to be executed n times, the time complexity is recorded as O(n)

V. example of logarithmic order O(logn)

int count = 1; while (count < n) { count *= 2 } // Since the count is multiplied by 2 each time, it is further from n. Exit the loop by 2^x = n program, then X = log2(n) // Time complexity is recorded as O(logn)

Vi. square order examples O(n^2) and O(m * n)

int i, j for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { / *Time complexity is O(1)Calculation sequence of */ } } // Since the inner loop is executed n times, the outer loop is executed n times, totaling O(n*n)

int i, j for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { / *Time complexity is O(1)Calculation sequence of */ } } // Since the inner loop executes n times, the outer loop also executes n times, totaling O(m*n)

int i, j for (i = 0; i < n; i++) { for (j = i; j < n; j++) { / *Time complexity is O(1)Calculation sequence of */ } } // When i = 0, the inner loop executes n times; when i = 1, the inner loop executes n-1 times // n + (n-1) + ... = n(n+1)/2 = n^2/2 + n/2 // According to the law, the time complexity is (n*n)

VII. Time spent on common complexity sorting from small to large

O(1) < O(logn) < O(n) < O(nlogn) < O(n*n) < O(n*n*n) < O(2^n) < O(n!) < O(n^n)