Quicksort is an improvement in bubble sorting. Proposed by C. A. R. Hoare in 1962. Its basic idea is: split the data to be sorted into two independent parts by one sort, and all the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence.
Quicksort is an improvement in bubble sorting. Proposed by C. A. R. Hoare in 1962. Its basic idea is: split the data to be sorted into two independent parts by one sort, and all the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence.
Set the array to be sorted to A [0]... A [N-1], first randomly select A data (usually the first data) as the key data, and then put all the smaller than it before it, all the numbers larger than it are placed behind it. this process is called a fast sorting. It is worth noting that quick sorting is not a stable sorting algorithm, that is, the relative positions of multiple identical values may change at the end of the algorithm.
The quick sorting algorithm is as follows:
- Set two variables I, J, when sorting starts: I = 0, J = N-1;
- Take the first array element as the key data and assign it to the key, that is, key = A [0];
- Start from J to search forward, that is, start from the back to search forward (J = J-1), find the first value less than the key A [J], and exchange with A [I;
- Search backward from I, that is, search backward from the beginning (I = I + 1), find the first A [I] greater than the key, and exchange with A [J;
- Repeat steps 3rd, 4, 5 until I = J; (step 4 is not found in the program when j = J-1, I = I + 1 until it is found. When I is found and switched, the position of the j pointer remains unchanged. In addition, when I = j, this process must be the end of the last loop completed by I + or j .)
For example, the values of array A to be sorted are as follows: (initial key data: X = 49) note that key X remains unchanged and will always be compared with X, no matter what position, the final goal is to put X in the middle and a small one in front and a large one in the back.