Professional Documents
Culture Documents
Four Concepts of Complexity Analysis
Four Concepts of Complexity Analysis
Answer analysis:
1. The best case time complexity is O(1)
2. Worst-case analysis:
The worst-case code execution times are related to the length of each array
The number of executions of the first call to insert is n,
The number of executions of the second call to insert is 2n,
The number of executions of the third call to insert is 2^2 * n
The number of executions of the kth call to insert is 2^(k-1) * n
The worst time complexity is O(n).
3. Average situation analysis
Each time the worst case is encountered, the array will be expanded twice. The original array is
imported into the new array. Although the length of the array becomes larger, the length of the
interval in which the insertion operation falls They are the same, they are 0~len-1, len~(2len-
1),...;
The insertion situation is still len+1: 0~len-1 and O(len) after the insertion; so the probability of
each insertion is: p = 1/len+1 ,
Finally, the weighted average time complexity is calculated as 1*p + 2*p+ + len*p + len * p =
O(1);
4. Amortized time complexity O(1)
And the amortized complexity is because each occurrence of O(len) is followed by len times
O(1), which is coherent, so O(len) is evenly distributed to the previous len times. , The amortized
complexity is O(1)