Introduction
The first time I learned that the reverse number is in the Advanced Algebra course. When I wanted to calculate the inverse number of a sequence, intuition was solved by the double cyclic O (n^2) violence. Now gradually the merging algorithm has a certain understanding, so decided to use C + + code to try sledgehammer.
Introduction to reverse order number
1 , 2 n n rank (for short), or general, n A separate element is a column called "A n rank ". For example, 1234 and 4312 4 24315 is a 5 rank.
In an n -level arrangement, if the front and back positions of a pair of numbers are opposite to the size order, that is, the previous number is greater than the subsequent number, then they are called an "inverse".
Example:
1,2,3,4become the natural permutation number for0
3,2,4,1a number of columns in reverse order have(3,2) (3,1) (2,1) (4,1)so the reverse number is4
Code implementation
#include <cstdio>#include<cstring>Const intN =4;//to test the size of an arrayintCnt//Global Variables voidMergeSort (int*a,intPintQint*T) { if(p+1>=Q)return; intm=p+ (Q-P)/2; MergeSort (a,p,m,t); MergeSort (a,m,q,t); //Merge for(intx=p,y=m,i=p;i<q;i++){ if(X<m&&y<q&&a[x]<a[y] | | y>=q) T[i]=a[x++];//go to ' left ' plus Else{T[i]= a[y++]; CNT+ = (m-x);//The emphasis here is to add a number to the right, and the number of elements to the left that have not been added to T } } for(inti=p;i<q;i++) A[i]=t[i];}intMain () {intT[n];//auxiliary Array, which is the extra Space cost O (N) inta[]={3,2,4,1}; CNT=0;//initial CNT is 0MergeSort (A,0, n,t); printf ("Number of reverse order:%d\n", CNT); return 0;}
Conclusion
Compared with the previous double cyclic violence method, we can prove that the time complexity of merging solution is O (NLGN). Therefore, when N is large, it can be found that this merging algorithm is significantly more efficient.
Recursive O (NLGN) solves reverse order number