Time complexity space complexity algorithm stability

1. Time complexity

1.1 Concept (time complexity: the number of execution statements)

The first thing to say is that the calculation of time complexity is not to calculate the specific running time of the program, but the number of times the algorithm executes the statement.

1.2 Calculation of time complexity (example)

(1) If the execution time of the algorithm does not increase with the increase of the problem size n, even if there are thousands of statements in the algorithm, the execution time is just a relatively large constant. The time complexity of this type of algorithm is O(1).

int x=1;
while (x <10)
{
    x++;
}

The number of executions of the algorithm is 10, which is a constant, and it is O(1) in terms of time complexity.

(2) When there are several loop statements, the time complexity of the algorithm is determined by the frequency f(n) of the innermost statement in the loop statement with the most nesting levels.

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

In this algorithm for loop, each time the outermost loop is executed, the inner loop must be executed n times. The number of executions is determined by n, and the time complexity is O(n^2).

2. Space complexity

2.1 Concept (Space Complexity: Temporary Space Size)

Space complexity is a measure of the amount of storage space that an algorithm temporarily occupies during its operation.

2.2 Calculation method:

①Ignore the constant and express it in O(1).
②The space complexity of the recursive algorithm = the depth of recursion N*the auxiliary space required
for each recursion. ③For a single thread, recursion has a runtime stack, and what is
required is the deepest recursion. The amount of space consumed by the stack, because the space consumed by the deepest recursion is enough to accommodate all its recursive processes.

3. Algorithm stability

Simply put: the same element does not change before and after sorting, it is stable.

Official statement:
Assume that there are multiple records with the same key in the sequence of records to be sorted. If sorted, the relative order of these records remains unchanged, that is, in the original sequence,
ri=rj, and ri is before rj , And in the sorted sequence, if ri is still before rj, the sorting algorithm is said to be stable; otherwise it is called unstable.

Guess you like

Origin blog.csdn.net/lqy971966/article/details/107367402