[Data Structures and Algorithms 03] Preferably, the worst average, the time complexity is amortized

Origin

  • /****
        In a disordered array (Array) of
        Find position of first occurrence of the variable x. If not found, returns -1
    ****/
    
    // n 表示数组array的长度
    int find(int[] array, int n, int x) {
        int i = 0;
        int pos = -1;
        for (; i < n; ++i) {
            if (array[i] == x) pos = i;
        }
        return pos;
    }

Analysis of the time complexity of this function is O (n)

  • Find a data in the array does not need to have to traverse the entire array every time again,
  • Because it is possible to find a way to be ahead of the end of the cycle.

So what we can do to optimize this lookup code

  • /****
        In a disordered array (Array) of
        Find position of first occurrence of the variable x. If not found, returns -1
    ****/
    
    // n-represents the length of the array of array 
    int Find ( int [] array, int n-, int X) {
         int I = 0 ;
         int POS = -1 ;
         for (; I <n-; ++ I) {
             IF (array [ I] == X) {
                POS = i;
                 BREAK ; // 've found, you do not have to keep looking up 
            }
        }
        return pos;
    }

So the question is, after such optimization, time complexity is O (n) do? ? ?

  • Probably for the first time to find, only cycle once, that time complexity is O (1)
  • Possible to find the last time, cycle n times, it becomes time complexity O (n)

Therefore, under different circumstances, the time complexity of this code is not the same

Thus, to represent the code complexity at different times in different situations, we need to introduce the concept of three

  • Best-case time complexity
  • The worst case time complexity
  • The average case time complexity

2

2

2

2

2

2

2

2

First, the best-case time complexity (best case time complexity)

In the best case execution time complexity of this code

"Cycle only once found a"

 

Second, the worst case time complexity (worst case time complexity)

In the worst case, the execution time of this code complexity

"Cycle n times to find."

 

Third, where the average time complexity (average case time complexity)

The best time complexity of the case and worst-case time complexity is the corresponding code complexity in extreme cases, the probability of occurrence is not large.

In order to better represent the complexity of the average case, we need to introduce another concept: the average time complexity of the case, referred to as the back of my average time complexity

1

1

1

1

Fourth, the complexity of shared equally time (amortized time complexity)

1

1

1

1

1

Guess you like

Origin www.cnblogs.com/tianxiaxuange/p/12285954.html
Recommended