(Algorithm) Dutch flag problem, the basis of quick sorting

Topic overview (Example 1)

Given an array  arr and a number  num  , it is required that the left part of the array be all numbers less than  num  , and the right part be all numbers greater than or equal to num. Requires time complexity  O(N)  , additional space complexity  O(1)  .

implement logic

Prepare two variables, one as the right boundary of the part less than num , and i , as a pointer. (assuming num = 3 here )

figure 1

Starting from the far left, i points to 1,  compared with num  , 1 < 3, then the boundary moves one position to the right, i++ ;

i points to 3, 3 = 3, then the boundary does not move, i++ ;

i points to 2, 2 < 3, then the boundary is shifted one bit to the right, 2 is exchanged with the number at the boundary position, i++ ;

figure 2 

 i-oriented 4 , 4 > 3 , i++ ;

 i points to 1, 1 < 3, the boundary is shifted one bit to the right, and 1 is exchanged with the number at the boundary position, i++ ;

 i points to 6, 6 > 3, the boundary does not move, i++ , out of range, return directly;

So far, the numbers smaller than  num  are all on the right side of the array, and the entire array is sorted.

Topic overview (Example 2, the real Dutch flag)

Given an array  arr  and a number num , it is required that the left part of the array be all numbers less than num, the middle part be equal to num  and the right part be all numbers greater than or equal to num. Requires time complexity O(N) , additional space complexity O(1) . (The reason why it is called the Dutch flag problem is because they are all three parts, so everyone is used to calling the Dutch flag)

 implement logic

  It is very similar to Example 1 above. We find the similarities and differences and then make improvements. When we encounter problems, we will think like this.

There is an extra piece equal to the part, and the pictogram is as follows

We prepare three variables, one as the right boundary of the less than part, one as the left boundary of the greater than part, and one as the traversal pointer.

In the same way, the two boundaries are at both ends, i starts from the left, and when it is greater than  num  , the left side of the larger part is moved to the left by one position, and the number at position i is exchanged. Don't worry about the middle position, and finally allocate it yourself.

Guess you like

Origin blog.csdn.net/qq_48860282/article/details/123995043