1. Calculate the number of reverse orders using a tree Array
Disadvantage: Only integers can be obtained in reverse order.
# Include "treearray. H"/* algorithm: returns reverse order pairs from a tree array. When element I is added, the value of a [I] with element I as the benchmark is + 1, from the end of the team to the first of the team, and the logarithm of the reverse order is + = getsum (I-1) each time you enter the team ), that is, the number of elements whose subscript is greater than it but whose values are smaller than it. Because the tree array cannot process the element whose subscript is 0, when each element enters + 1, other programs should adjust accordingly. After finding the number of reverse pairs of the original sequence, move the first element to the end of the team. The reverse logarithm is the original reverse logarithm + the number of elements larger than I-the number of elements smaller than I, because it is 0 .. n, it is easy to directly calculate */INT nixushu (INT array [], int N) {treearray TA (1); TA. clear (); int I, sum = 0; for (I = n-1; I> = 0; I --) {TA. modify (array [I] + 1, 1); sum = sum + Ta. sum (array [I]);} return sum ;}
2. Calculate the number of reverse orders by means of Merge Sorting
Disadvantage: the value in the array is changed.
#include <iostream>using namespace std;#define MAX 50005int rs, tar[MAX];void merge(int Array[], int l,int m,int r){ int l1=l,l2=m+1,pp=0; while(l1<=m&&l2<=r){ if(Array[l1]<=Array[l2]){ tar[pp++]=Array[l1++]; }else{ tar[pp++]=Array[l2++]; rs+=m-l1+1; } } while(l1<=m)tar[pp++]=Array[l1++]; while(l2<=r)tar[pp++]=Array[l2++]; for(int i=l,j=0;i<=r;i++,j++){ Array[i]=tar[j]; } } void mergesort(int Array[], int l,int r){ if(l>=r)return; int m=(l+r)/2; mergesort(Array, l, m); mergesort(Array, m+1, r); merge(Array, l, m, r); } int NiXuShu(int Array[], int n){rs = 0;mergesort(Array, 0, n-1);return rs;}