Explanation of the partition Function in quick sorting

Source: Internet
Author: User

Explanation of the partition Function in quick sorting

The essence of quick sorting lies inpartitionFunction 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.iThe pointer traverses the entire array as long as it points to lesspivotExchange 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 ;}

TwiceswapIn orderpivotSave the data to the last location and complete it once.partitionpivotRestorestoreIndexPosition. Because all elements before it are smaller than it, and all subsequent elements are greater than it.

If noswap, ThenstoreIndexWill point to greater than or equalpivotDoes not guarantee that all elements after it are greaterpivot(This ensures that all of the earlier versions are less than the same ).storeIndexOnce the position element is fixed, it will not change until the program ends. Therefore, you need to use two exchanges for temporary storage.pivotElement.

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.