[The Order of the sword] the reverse order in the array

Source: Internet
Author: User

The title describes the two numbers in the array, and if the previous number is greater than the number that follows, the two numbers form an inverse pair.  Enter an array to find the total number of reverse pairs in this array. Analysis: Using the idea of merge sorting, divided into 2 parts, each part according to from the big to the small sort, then compares the left side of the a[i] and the right side of the b[j] if A[I]>B[J], then a[j] greater than b[j]~b[right], to produce right-j+1 group reverse order. If A[J]<=B[J], do not produce reverse order. It also updates the left-to-right part of the array, sorts it from the large to the small, and then sorts the array with the sort number and the larger array, while calculating the number of reverse groups.
classSolution {Private:        intMerge (vector<int>& data,intLeftintMidintRight ) {Vector<int>Tmpvec; intCNT =0; inti = left, J = mid +1; //sort Vecotr from big to small             while(I <= mid && J <=Right ) {                if(Data[i] >Data[j]) {CNT+ = (Right-j +1);                    Tmpvec.push_back (Data[i]); I++; }                Else{tmpvec.push_back (data[j]); J++; }            }             while(I <=mid) {tmpvec.push_back (data[i]); I++; }             while(J <=Right )                {Tmpvec.push_back (data[j]); J++; }            //copy TMP data to original data             for(intK =0; K <= (Right-left); k++) {data[k+ Left] =Tmpvec[k]; }            returnCNT; }        intInversepairs (vector<int>& data,intLeftintRight ) {            if(data.size () = =0)                return 0; if(Left >=Right )return 0; intMid = (left + right)/2; intCNT =0; CNT+=inversepairs (data, left, mid); CNT+ = Inversepairs (data, Mid +1, right); CNT+=merge (data, left, Mid, right); returnCNT; }     Public:        intInversepairs (vector<int>data) {            returnInversepairs (data,0, Data.size ()-1); }};

[The Order of the sword] the reverse order in the array

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.