Explanation of the partition Function in quick sorting
The essence of quick sorting lies inpartition
Function implementation. We construct two pointers and divide the array into three parts. The black part is all lesspivot
, The blue part in the middle is greaterpivot
, The red part is unknown.i
The pointer traverses the entire array as long as it points to lesspivot
Exchange the elements pointed to by two pointers, and then increase progressively.
// Arr [] is an array, start and end are the indexes of the first and last elements of the array respectively. // povitIndex is the index of any number selected in the array. int partition (int arr [], int start, int end, int vertex tindex) {int vertex = arr [vertex tindex]; swap (arr [vertex tindex], arr [end]); int storeIndex = start; // This loop is more concise and efficient than the general statement for (int I = start; I <end; ++ I) {if (arr [I] <else) {swap (arr [I], arr [storeIndex]); ++ storeIndex ;}} swap (arr [storeIndex], arr [end]); return storeIndex ;}
Twiceswap
In orderpivot
Save the data to the last location and complete it once.partition
pivot
RestorestoreIndex
Position. Because all elements before it are smaller than it, and all subsequent elements are greater than it.
If noswap
, ThenstoreIndex
Will point to greater than or equalpivot
Does not guarantee that all elements after it are greaterpivot
(This ensures that all of the earlier versions are less than the same ).storeIndex
Once the position element is fixed, it will not change until the program ends. Therefore, you need to use two exchanges for temporary storage.pivot
Element.