"Algorithm 32" computes the reverse order in the array

Source: Internet
Author: User

Problem description

Set A[1...N] is an array, if for i < J have a[i] > a[j], then a[i] and a[j] constitute a pair of reverse order. Given an array, calculates the number of reverse pairs in the array. For example, array a[] = {1, 4, 3, 2}, then {4, 3} {4, 2} {3, 2} are reverse pairs, return 3.

Solution One: Brute Force solution

Two for loops enumerate all the pairs, and if they are in reverse order, then count++, and finally the count is returned. Time complexity O (n^2), the code is as follows:

1#include <iostream>2#include <string>3#include <vector>4 using namespacestd;5 6 intCountinversions (Constvector<int>&a)7 {8     intCNT =0;9      for(size_t i =0; I < a.size (); i++)Ten     { One          for(size_t j = i +1; J < A.size (); J + +) A         { -             if(A[i] > a[j]) cnt++; -         } the     } -     returnCNT; - } -  + intMain () - { +     intA[] = {1,4,3,2}; Avector<int> V (A, A +4); atcout << countinversions (v) <<Endl; -     return 0; -}
Solution II: Divide & Conquer (Modify merge sort)

This solution is mentioned in study questions 2-4 of the section "Introduction to Algorithms" in the merge sequence. The original question is as follows:

Set A[1...N] is an array containing n different numbers, if in the case of I < J, there is a[i] > A[j], then (i, J) is called a reverse order (inversion) in a.

(a) a list of 5 reverse pairs of <2, 3, 8, 6, 1>.

Answer: <2, 1> <3, 1> <8, 6> <8, 1> <6, 1>

(b) If the elements of the array are taken from the collection {1, 2, 3, ..., n}, what about the array containing the most reverse order? How many reverse order does it contain?

A: n elements up to n (n-1)/2 arrays, in the worst case, all pairs are in reverse order, thus up to N (n-1)/2 reverse. This array is in reverse order {n,n-1, ..., 2, 1}

(c) What is the relationship between the run time of the insert sort and the number of reverse pairs in the input array? Explain your reasons.

A: The core procedure for inserting a sort is as follows, and you can see that the inner loop is actually executed because {i, J} is in reverse order, in other words, after the inner loop is executed, the inverse of {i, J} is eliminated, so the total number of loops in the order is inserted in the inverse of the array.

1  for(inti =1; I < n; ++i)2 {3     intx =A[i];4      for(intj = i-1; J >=0&& a[j] > x; --j)5     {6A[j +1] =A[j];7     }8A[j +1] =x;9}

(d) An algorithm that can use the worst-case run time of O (NLOGN) to determine the inverse logarithm of any permutation of n elements. (Hint: Modify merge Sort)

The basic idea of merge sort is Divide & Conquer: Divide the array into the left and right parts, merge sort to the Ieft part, merge to sort the part, and then merge about two arrays into a new array to complete the sorting. According to this basic idea, we can also apply to calculate the inverse of the pair, suppose we divide the array into two parts, and I tell you the left side of the reverse order to have inv1, the right side of the reverse pair have inv2, as shown

Then the remainder of the reverse is necessarily a number appears on the left part, a number appears on the right part, and satisfies the left part of the number A[i] > A[j], as shown, it is worth explaining is: the left and right two sort or not, will not affect the reverse logarithm in this case, Because the left and right two parts of the sorting is only to eliminate the two parts of the internal reverse order, and for A[i] from the left, A[j] from the wrong side of the reverse order, respectively, after sorting or reverse

Then we need to calculate in the process of the Merge A[i], a[j] respectively from the left and right two parts of the reverse logarithm, as shown, if all A[i] is less than the first number of b[j], obviously there is no reverse order. only if a[i] > B[j] is in reverse order, because we have pre-a[] and b[] already sequenced, and so if a[i] > B[j], then all A[ii] (ii > I) also meet a[ii] > B[j), Also is said and B[j] the number of reverse order has {A[i], a[i+1]...a[end]}, so the number of reverse order increase End-i + 1, so we each encounter a[i] > B[j] situation, reverse logarithmic increase (end-i + 1) can be.

The framework diagram of the entire algorithm can be represented as follows:

The code for the entire algorithm is as follows, the time complexity of course O (NLOGN)

1#include <iostream>2#include <string>3#include <vector>4 using namespacestd;5 6 7typedefLong LongLlong;8 9Llong Mergeandcount (vector<unsignedint> &a,intLeftintMidintRight, vector<unsigned.int> &temp);TenLlong Mergesortandcount (vector<unsignedint>& A,intLeftintRight, vector<unsigned.int>&temp); OneLlong Countinversions (vector<unsignedint>&a); A  - intMain () - { the     //freopen ("data.in", "R", stdin); -  -     intN; -CIN >>N; +  -vector<unsignedint> A (N,0); +      for(inti =0; i < N; ++i) A     { atCIN >>A[i]; -     } -  -Llong result =Countinversions (a); -cout << Result <<Endl; -     return 0; in } -  toLlong Mergeandcount (vector<unsignedint> &a,intLeftintMidintRight, vector<unsigned.int> &temp) + { -     inti =Left ; the     intj = Mid +1; *     intK =Left ; $Llong cnt =0;Panax Notoginseng  -      while(I <= mid && J <=Right ) the     { +         if(A[i] <=A[j]) A         { thetemp[k++] = a[i++]; +         } -         Else  $         { $temp[k++] = a[j++]; -CNT + = Mid-i +1;//Key Step -         } the     } - Wuyi      while(I <= mid) temp[k++] = a[i++]; the      while(J <= right) temp[k++] = a[j++]; -  Wu      for(i = left, I <= right; + +)i) -     { AboutA[i] =Temp[i]; $     } -     returnCNT; - } -  ALlong Mergesortandcount (vector<unsignedint>& A,intLeftintRight, vector<unsigned.int>&temp) + { the     //Base Case -     if(left >= right)return 0; $  the     intMid = (left + right)/2; the      theLlong InversionCnt1 =Mergesortandcount (A, left, mid, temp); theLlong InversionCnt2 = Mergesortandcount (A, mid+1, right, temp); -Llong mergeinversioncnt =Mergeandcount (A, left, mid, right, temp); in  the     returnInversionCnt1 + InversionCnt2 +mergeinversioncnt; the } About  theLlong Countinversions (vector<unsignedint>&a) the { the     intn =a.size (); +vector<unsignedint>Temp (A.begin (), A.end ()); -Llong ans = mergesortandcount (A,0, N-1, temp); the     returnans;Bayi}
Reference documents

[1] "Introduction to Algorithms" Chinese second edition, p24,2-4 reverse order.

[2] http://blog.csdn.net/qcgrxx/article/details/8005221

[3] Www.cs.umd.edu/class/fall2009/cmsc451/lectures/Lec08-inversions.pdf

"Algorithm 32" computes 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.