DS Part Two: Predefined Constants (Description in C++), Algorithm Time Complexity Analysis Examples

Predefined constant

  • To be used in the following data structure description:
    here is the pre-defined description of C++
    // 函数结果状态
    #define OK 1
    #define ERROR 0
    #define OVERFLOW -2
    //Status 是函数返回值类型,值为返回的状态
    typedef int Status
    //这里Status其实就是int
  • The pre-defined description of Python (not very good yet...it looks like python has no pre-defined)

Algorithm time complexity analysis example (non-recursive algorithm)

Theorem 1.1 in the book:
If f(n) = a m n m + a m-1 n m-1 +…+a 1 n+a 0 , is a polynomial of degree m,
then T(n) = O(n m ) In
other words, ignore the coefficients of low-power terms and high-power terms

Constant order

{
    
    x++;s=0;}

for (i=0;i<l0000; i++) {
    
    
	x++; 
	s=0;
	}

The frequency of the two sentences and the frequency of the loop body are both 1.
The execution time of the algorithm is a constant independent of the problem size n,
T(n) = O(1), a constant order.
`It
should be noted that if the sentence frequency in the algorithm is a certain constant.
No matter how large this constant is, the time complexity of the algorithm is O(1).

Linear order

for (i=0; i<n; i++) {
    
    
	x++; 
	s=0;
	} 

The frequency of the two basic sentences in the loop is f(n)=n,
T(n)= O(n), linear order.

Square order (&&/and) cubic order k-th order

x=0;y=0;
for (k=l; k<=n; k++)
	x++;
for(i=l;i<=n;i++)
	for(j=l;j<=n;j++)
		y++;

For loop statements, only the number of executions of the statements in the loop body needs to be considered. The most frequent statement in the
above program segment is (6)y++;, the frequency is f(n)=n 2 ,
T(n)= O(n 2 ), square order.

x = 1
for(i=1; i<=n;i++)
	for(j=1;j<=i;j++)
		for(k=1;k<j;k++)
			x++;

The most frequent statement in this program segment is (5)x++;
then there is such a picture in the book:

Insert picture description here
The first n terms and formulas of the arithmetic sequence and the (first n terms) sum of squares formula are used
Insert picture description here

This is a mathematical problem. You can refer to this netizen’s illustrated explanation
or let me say something about it:
Come, take a deep breath, imagine:
when i=1, (5) execute once
when i=2, (5) execute 1+2 times
when i= 3. (5) Execute 1+2+3 times
...
For i=n, ​​(5) Execute (1+n)n/2 times.
So as long as you add up all the execution times above, it will be the scale of the problem,
which is the calculation:
Insert picture description here

T(n)= O(n 3 ), cubic order.

Then the k-th order is the extension of the second and third order

Logarithmic order

for (i=l; i<=n; i=i*2) {
    
    
	x++;
	s=0;
	} 

Suppose the frequency of two basic sentences in the loop body is f(n), then there are
2 f(n) <=n, both sides take the logarithm of 2 at the same time ,
f(n)<=log 2 n,
T(n) = O(log 2 n), logarithmic order.

Guess you like

Origin blog.csdn.net/m0_46156900/article/details/114306828