Sorting: quick sort (hoare version)

Table of contents

Quick sort:

concept:

Animation analysis: 

Code:

Code analysis: 

Code features:

common problem:


Quick sort:

concept:

Quick sort is a binary tree structure exchange sorting method proposed by Hoare in 1962. Its basic idea is:

Take any element in the sequence of elements to be sorted as the reference value, and divide the set to be sorted into two subsequences according to the sorting code.

All elements in the left subsequence are less than the reference value, all elements in the right subsequence are greater than the reference value, and then the process is repeated for the left and right subsequences until all elements are arranged in the corresponding positions.​ 

Animation analysis: 

As shown in the animation above, the leftmost element of the array is selected as the base value key, and two traversal variables are set at both ends of the array to traverse the array.

The traversal on the left is responsible for finding a value larger than the key, and the traversal on the right is responsible for finding a value smaller than the key.

When the left side encounters a value larger than key, stop, wait for the right side to encounter a smaller value than key, and then exchange the elements pointed to by the two, perform multiple operations, wait until the two meet, and then move the leftmost key The value and the element at the meeting position are exchanged.

The purpose of this is to use the key value to separate the entire array. The elements at the left end are smaller than the key, and the elements at the right end are larger than the key.

Then, perform the same operations on the two separated parts separately, and continue to separate the two parts into two parts until the position can no longer be separated.​  

Code:

Code analysis: 

Code features:

common problem:

  1. What should I do when I encounter the equals option?
  2. Will the key value change?
  3. When meeting, it may not stop if the conditions are not met.
  4. key is easy to write as a local variable
  5. Is the initial subscript position of the left-end traversal variable in the first pass 0 or 1?
  6. Do we need to stop the forward loop of traversing variables when we encounter equal elements?

Guess you like

Origin blog.csdn.net/2301_76445610/article/details/134863655