The time complexity of the division and conquer method for finding the reverse logarithm is O (n * logn)
Ideas:
In the process of merge and sort by Division, one step is to extract the small element from both the left and right arrays and put it in the tmp [] array each time.
The array on the right is actually the element on the right of the original array. When the elements on the right are taken without the elements on the left, the remaining elements on the left are larger than those on the first element on the right, that is, they can constitute a reverse order. Assume that there are n remaining elements on the left side, then the reverse logarithm + n.
In addition, if all the elements on the right are obtained, but there are still elements on the left, the remaining elements on the left have been added to the backward direction in the previous operation, and you do not need to add it again.
The following code combines sorting and reverse order logarithm:
Code1:
Merge Sorting
#include
#include
#includeusing 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:
Reverse Order logarithm:
Cnt indicates the number of reverse logarithm
#include
#include
#includeusing 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 provided by LRJ is hard to understand ....