Time complexity & space complexity & stability

table of Contents

1. Comparison of various algorithms

2. Definition of algorithm instability

3. Several unstable algorithms

1. Comparison of various algorithms

2. Definition of algorithm instability

  Definition: Before sorting, there are two numbers equal, but after sorting ends, the two of them may change the order.

  Explanation: In a queue to be sorted, A and B are equal, and A is in front of B, and after sorting, A is behind B. At this time, we say that this algorithm is unstable.

3. Several unstable algorithms

  1) Why the fast row is unstable

    3 2 2 4 After the first quick sort, the result is: 2 2 3 4 (The 2 in position 3 runs to the position 1 after the first sort)

  2) Why is the heap sort unstable  

    If the top 3 of the stack is output first, then the 27 of the third layer (the last 27) runs to the top of the stack, then the stack is stable, and the output of the top of the stack is continued.

    This shows that the following 27 is output before the second position 27, unstable

        

  3) Why the selection order is unstable

    5 8 5 2 9 For the first time, it is assumed that the 5 in position 1 is the smallest, but the actual smallest is the 2 in position 4

    After the first sorting: 2 8 5 5 9 before the number 5 in position 1 ran behind the number 5 in position 3

Note:

  time complexity

    There are several layers of for loops, and the time complexity is several times of n.

    Each cycle halving is nlogn

    As long as you see the loop halving, there is a logn

  Space complexity

    Apply for a new memory space

    n = 1 # space complexity o (1)

    list = [1,2,3,4] # space complexity o (n)

Guess you like

Origin www.cnblogs.com/xinzaiyuan/p/12697008.html