For details about Merge Sorting, see "Introduction to algorithms"-Divide and conquer law. In the following example, we use the merge method to calculate the number of reverse orders for the 2299 questions in poj:
/** The question indicates the number of exchanges that require Bubble sorting. Algorithm used: sort by merge to calculate the number of reverse orders. # This question fully demonstrates that even if merge itself may not use much, the idea of separation and metallurgy is omnipresent. **/# include <stdio. h> int left [250003], right [250003]; long count; void Merge (int * a, int P, int Q, int R) {int I, j, k, N1, N2; n1 = Q-p + 1; N2 = r-Q; for (I = 0; I <N1; I ++) {left [I] = A [p + I] ;}for (I = 0; I <N2; I ++) {right [I] = A [q + I + 1];} left [N1] = right [n2] = 0x7fffffff; I = J = 0; For (k = P; k <= r; k ++) {If (left [I] <= right [J]) {A [k] = left [I]; I ++ ;} else {A [k] = right [J]; j ++; count + = n1-i;/** this step is added in the merge sort, used to count the number of reverse orders **/} return;} void mergesort (int * a, int P, int R) {int Q; If (P <R) {q = (p + r)/2; mergesort (A, p, q); mergesort (A, q + 1, R); merge (A, p, q, r);} return;} int main () {int N, I, a [500001]; while (scanf ("% d", & N) {COUNT = 0; for (I = 0; I <n; I ++) {scanf ("% d", & A [I]) ;} mergesort (, 0, n-1); printf ("% LLD/N", count );}}