Ideas:
In the process of merging and sorting, one step is to remove the small element from the left and right two arrays in the tmp[] array.
The array on the right is actually the element on the right side of the original array. When you take the element to the right without taking the element to the left, the remaining elements on the left side are larger than the first element on the right, i.e. they can form an inverse pair. Assuming that there are now n elements left on the right, the inverse logarithm is +n.
In addition, if all elements on the right side are exhausted, but there are still elements remaining on the left side, the remaining elements on the left side have been added to the inverse pair in the previous operation, no need to add
The following is a two-part code for merging sorting and reverse order:
Code1:
Merge sort
#include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int n;int a[20];void Query (int a[], int first, int mid, int last, int tmp[]) {int i = first, j = mid+1; int k = 0; while (I <= mid && J <= last) {if (A[i] < a[j]) tmp[k++] = a[i++]; else tmp[k++] = a[j++]; } while (I <= mid) {tmp[k++] = a[i++]; } while (J <= last) {tmp[k++] = a[j++]; } for (int id = 0; ID < K; id++) {A[first + id] = Tmp[id]; }}void Merge_sort (int* A, int L, int R, int* tmp) {if (L < R) {int M = L + (r-l)/2; Merge_sort (A,L,M,TMP); Merge_sort (A,M+1,R,TMP); Query (A,L,M,R,TMP); }}int Main () {scanf ("%d", &n); for (int i = 0; i < n; i++) {scanf ("%d", &a[i]); } int tmp[20]; Merge_sort (A,0,N-1,TMP); for (int i = 0; i < n; i++) {printf ("%d", a[i]); } printf ("\ n"); return 0;}
Code2:
To find the inverse logarithm:
CNT indicates the number of reverse logarithm
#include <cstdio> #include <cstring> #include <algorithm>using namespace Std;int n;int a[20];int cnt; void query (int a[], int first, int mid, int last, int tmp[]) {int i = first, j = mid+1; int k = 0; while (I <= mid && J <= last) {if (A[i] <= a[j]) tmp[k++] = a[i++]; else{tmp[k++] = a[j++]; CNT + = mid-i+1; }} while (I <= mid) {tmp[k++] = a[i++]; } while (J <= last) {tmp[k++] = a[j++]; } for (int id = 0; ID < K; id++) {A[first + id] = Tmp[id]; }}void Merge_sort (int* A, int L, int R, int* tmp) {if (L < R) {int M = L + (r-l)/2; Merge_sort (A,L,M,TMP); Merge_sort (A,M+1,R,TMP); Query (A,L,M,R,TMP); }}int Main () {scanf ("%d", &n); for (int i = 0; i < n; i++) {scanf ("%d", &a[i]); } int tmp[20]; CNT = 0; Merge_sort (A,0,N-1,TMP); for (int i = 0; i < n; i++) {printf ("%d", a[i]); } prinTF ("cnt =%d\n", CNT); printf ("\ n"); return 0;}
The code given by LRJ is poorly understood ....
The number of time complexity of finding the logarithm of reverse order by divide-and-conquer method is O (N*LOGN)