(Java data structure) time complexity space complexity

Algorithm efficiency

There are two types of algorithm efficiency analysis: the first is time efficiency, and the second is space efficiency. Time efficiency is called time complexity, while space efficiency is called
space complexity. Time complexity mainly measures the running speed of an algorithm, while space complexity mainly measures the extra space required by an algorithm.

time complexity

concept

The time complexity of the algorithm is a mathematical function, and the number of executions of the basic operations in the algorithm is the time complexity of the algorithm.

Asymptotic notation for big O

1. Replace all additive constants in run time with the constant 1.
2. In the modified running times function, only the highest order term is kept.
3. If the highest order item exists and is not 1, remove the constant multiplied by this item. The result is big O order.

The time complexity of some algorithms has best, average and worst cases:
worst case: maximum number of runs (upper bound) for any input size
average case: expected number of runs for any input
size best case: minimum for any input size Number of runs (lower bound)

The general case is concerned with the worst-case run of the algorithm.

Examples of common time complexity calculations

// 计算bubbleSort的时间复杂度
void bubbleSort(int[] array) {
    
    
for (int end = array.length; end > 0; end--) {
    
    
    boolean sorted = true;
    for (int i = 1; i < end; i++){
    
    
      if (array[i - 1] > array[i]){
    
    
         Swap(array, i - 1, i);
         sorted = false;
      }
    }
    if(sorted == true) {
    
    
       break;
    }
  }
}

Worst case: the array is in descending order, assuming that the array has n elements, the number of executions: n-1+n-2+n-3+...+1=n(n-1)/2. The time complexity of the worst
case is O(n^2).

Best case: the array is in ascending order, no exchange is required after the first pass, and the number of executions is n-1.
The best case time complexity is O(n).

Time complexity of recursion = number of recursions * number of executions after each recursion

// 计算斐波那契递归fibonacci的时间复杂度?
int fibonacci(int N) {
    
    
return N < 2 ? N : fibonacci(N-1)+fibonacci(N-2);
}

insert image description here

space complexity

Space complexity is a measure of the amount of storage space temporarily occupied by an algorithm during operation.
It can be understood as additional storage space.

/
/ 计算斐波那契递归fibonacci的空间复杂度?
int fibonacci(int N) {
    
    
return N < 2 ? N : fibonacci(N-1)+fibonacci(N-2);
}

insert image description here

The space complexity is O(n).

Guess you like

Origin blog.csdn.net/qq_63983125/article/details/126744330