Really some sort of sorting algorithm-quick sorting

The simple and crude of bubbling and selection sorting may not be called an algorithm in the eyes of some people. Now we have to enter a more elegant sorting algorithm, quick sorting. It uses the divide and conquer (Divide and Conquer, D & G) strategy to be applied to recursive calls. The quick sort dare to say that he is fast, and it is indeed much faster than the choice sort. Bubbling and selection sorting, especially selection sorting is a very natural sorting algorithm, and quick sorting is not something that ordinary people will come up with at will.

The deduction of quick sort needs to use recursion to think about the problem of loops. However, I have always tried to use loops to avoid recursive calls. What is interesting is that functionally compiled languages ​​such as Haskell have no loops at all, and can only write loops using recursion. effect. Let's look at a simple example. For example, to increase from 1 to 100, we will naturally use a loop to accumulate from 1 to 100. If it is replaced by recursion, see the following code

1
2
3
4
5
6
7
8
def summary ( arr ) :
     if len ( arr ) == 0 :
         return 0
     else :
         return arr [ 0 ] + summary ( arr [ 1 : ] )
 
 
print ( summary ( items = list ( range ( 1 , 101 ) ) ) )    # 5050

Recursion helps us decompose big problems into small problems. The thinking of the above code is that the sum of the array is always a single element plus the sum of the remaining element lists until the final element list is empty (and the sum is 0).

Guess you like

Origin www.cnblogs.com/wgq1233/p/12735578.html