The essence of quick sorting is in the partition implementation of the function. We build two pointers, divide the array into three parts, the black part is all less than pivot the middle blue part is greater than pivot the red part is unknown. The i pointer traverses the entire array, as long as it points to an element that is smaller than the pivot two pointer to the element that is pointing, and then increments.
//arr[] array, start, end the index of the first element and the last element, respectively, for the array//Povitindex the index of any selected number in the array int Partition(intArr[],intStartintEndintPivotindex) {intPivot = Arr[pivotindex]; Swap (Arr[pivotindex], arr[end]);intStoreindex = start;//This cycle is simpler and more efficient than the general wording for(inti = start; I < end; ++i) {if(Arr[i] < pivot) {Swap (Arr[i], arr[storeindex]); ++storeindex; }} swap (Arr[storeindex], arr[end]);returnStoreindex;}
Two times swap is to place the pivot last position first, and partition then restore to the point where it was completed once pivot storeIndex . Because the element before it is smaller than it, then it is larger than it.
If you do not have these two times swap , then you storeIndex will point to pivot an element that is greater than or equal, and there is no guarantee that the elements after it are greater than pivot (guaranteed to be less than before). storeIndexonce the elements of the position are fixed until the end of the program will no longer change, it is necessary to use two swap staging pivot elements.
The partition function in fast sorting