Merge sort to find the number of reverse order
In one 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. The total number of reverse order in a permutation is called the inverse number of the permutation. The total number of reverse order in a permutation is called the reverse number of this arrangement. That is, for n different elements, the first rule between each element has a standard order (for example, n different natural numbers, can be specified from small to large for the standard order), so in any one of the n elements, when the order of a two elements and the standard order is not the same, said there are 1 reverse. The total number of reverse order in a permutation is called the reverse number of this arrangement.
1#include <cstdio>2#include <cmath>3#include <cstring>4#include <iostream>5#include <algorithm>6 using namespacestd;7 intCount;8 inttemp[ -];9 voidMergearray (intA[],intFirstintMidintLast )Ten { One intI=first,j=mid+1; A intm=mid,n=Last ; - intk=0; - while(I<=m && j<=N) the { - if(A[i] <A[j]) -temp[k++]=a[i++]; - Else + { -temp[k++]=a[j++]; + //A[j] and each of the preceding numbers can be a number of reverse Acount+=m-i+1; at } - } - while(i<=m) temp[k++]=a[i++]; - while(j<=n) temp[k++]=a[j++]; - for(i=0; i<k;i++) a[first+i]=Temp[i]; - } in voidMergeSort (intA[],intFirstintLast ) - { to //Two-way merge + if(first<Last ) - { the intMid = (first+last)/2; *MergeSort (A,first,mid);//Merge left $MergeSort (a,mid+1, last);//Right MergePanax NotoginsengMergearray (A,first,mid,last);//then merge the two ordered series, in which the inverse number of the function is accumulated - } the } + A intMain () the { + inta[ -],n; -Cin>>N; $ for(intI=0; i<n;i++) $Cin>>A[i]; -Count=0;//Initialize an inverse number of 0 -MergeSort (A,0, N-1);//the 0-n is merged and sorted, and the number of reverse order is accumulated. theprintf"the inverse number pairs are:%d\n", Count); - return 0;Wuyi}
Merge Sort _ reverse order number