Classic algorithm--reverse order in the array

Source: Internet
Author: User

I. Description of the topic

In the array of two digits, if the previous number is greater than the number that follows, then these two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array.

Second, the method of solving problems using the idea of merging sorting, first divides the array into sub-arrays, first counts the number of reverse pairs within the subarray, and then counts the number of inverse pairs between the two adjacent sub-arrays. Note After you merge two sorted sub-arrays, you update the array.


Class Solution {Public:int inversepairs (vector<int> data) {int n=data.size ();    return process (data,0,n-1);             } int Process (vector<int>& data,int Start,int end) {//recursive termination condition if (start>=end) {        return 0; }//merge sort, and calculate the inverse logarithm vector<int> copy (data);        Array copy, for merge sort int mid= (start+end)/2;        int left=process (DATA,START,MID);                int right=process (data,mid+1,end); int p=mid;//p initializes the subscript int q=end;//q to the last digit of the first half, initializes the subscript int index=end;//the last digit of the second half, and initializes the subscript of the secondary array to the last int count            =0;//record the number of reverse pairs while (P>=start && q>=mid+1) {if (Data[p]>data[q])                {copy[index--]=data[p--];            Count+=q-mid;            } else {copy[index--]=data[q--];        }} while (P>=start) copy[index--]=data[p--]; while (Q>=mid+1) copy[index--]=data[q--];    for (int i = start; I <= end; i++) {Data[i] = copy[i];//Update Merge sorted sub-array} return (Left+right+count); }};



Classic algorithm--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.