The partition function in fast sorting

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.