Write RecursionProgramYou must pay attention to the logic of the recursive body, and assume that the sub-problem has been solved.
The Helper function only needs to solve the current layer's self-asked body well. Don't think too much about the hierarchy. Of course, there will be multi-level considerations for special recursion requirements.
Merge (int l, int M, int R, int * ){
L-> m
M + 1-> r to be merged
When calculating the number of Reverse Order pairs, you can count the reverse order logarithm in the parallel process.
L [] ordered, R [] ordered
Then, when l [I] <= R [J], the reverse logarithm is not required to be accumulated.
Otherwise, l [I]> r [J] indicates that L [I]-> L [len_of_leftpart] is in reverse order with R [J. So when inserting R [J], the number of Reverse Order pairs found is LEN_OF_LEFTPART-I + 1.
Rules on both sides and complete
Return the number of reverse pairs in the current merging process.
}
Merge_sort (int l, int R, int * ){
Int CNT = 0, M = (L + r)> 1;
If (L <r ){
CNT + = merge_sort (L, M, a); the left direction has several reverse order pairs.
CNT + = merge_sort (m + 1, R, a); when the right direction is set, there are several reverse order pairs.
CNT + = merge (L, M, R, a); at present, there are several reverse order pairs, which are assumed to be ordered on the right and left.
}
Return CNT;
}
Source code:
// ================================================ ==============================================
// Name: integerpartition. cpp
// Author: jry
// Version:
// Copyright: Your copyright notice
// Description: Hello world in C ++, ANSI-style
// ================================================ ==============================================
# Include <iostream>
# Include <stdio. h>
# Include <stdlib. h>
Using namespace STD;
Int merger (int l, int M, int R, int * ){
Int llen = m-L + 1, rlen = r-m;
Int * l = new int [(llen)];
Int * r = new int [(rlen)];
Int I = L, j = 0, K = 0, ttcnt = 0;
For (; I <= m; I ++) L [J ++] = A [I];
For (j = 0; I <= r; I ++) R [J ++] = A [I];
I = J = 0;
K = L;
While (I <llen & J <rlen ){
If (L [I] <= R [J]) A [k ++] = L [I ++];
Else {
A [k ++] = R [J ++];
Ttcnt + = llen-I;
}
}
While (I <llen) A [k ++] = L [I ++];
While (j <rlen) A [k ++] = R [J ++];
Delete [] (L );
Delete [] (R );
Return ttcnt;
}
Int merger_sort (int l, int R, int * ){
Int M = (L + r)/2;
Int tcnt = 0;
If (L <r ){
Tcnt + = merger_sort (L, M, );
Tcnt + = merger_sort (m + 1, R, );
Tcnt + = merger (L, M, R, );
}
Return tcnt;
}
Int main (){
Int A [] = {4, 1, 2, 3, 5, 1 };
Bool testmsort = false;
Int n = sizeof (a)/sizeof (INT );
If (testmsort) {for (INT I = 0; I <n; I ++) cout <A [I] <""; cout <Endl ;}
Cout <"reverse logarithm:" <merger_sort (0, n-1, A) <Endl;
Cout <"done" <Endl; // prints done
Return 0;
}