The design uses the time complexity O (nlgn)AlgorithmCount the reverse order pairs in the array whose length is N.
The core idea is to modify the Merge Sorting Algorithm, because when merging, the elements in two consecutive small arrays are compared.
# Include <stdio. h> # include <string. h> # include <time. h> # define buffer_size 10 void Merge (int * a, int P, int Q, int R, int * CNT) {int I = 0; Int J = 0; int K = 0; int n1 = Q-p + 1; int n2 = r-Q; int n = N1 + N2; int B [N1 + 1]; int C [n2 + 1]; memset (B, 0, sizeof (B); memset (C, 0, sizeof (c); B [N1] = buffer_size; // The Sentinel element. Do not overflow C [n2] = buffer_size; // The Sentinel element. Do not overflow for (I = P, j = 0; I <= Q; I ++) {B [J] = A [I]; j ++;} for (I = q + 1, K = 0; I <= R; I ++) {C [k] = A [I]; k ++ ;}for (I = P, j = 0, K = 0; I <= R; I ++) {If (B [J] <= C [k]) {A [I] = B [J]; j ++ ;} else {A [I] = C [k]; k ++; (* CNT) ++; // reverse order, Count }} void mergesort (int *, int P, int R, int * CNT) {int q = 0; If (P> = r) {return;} q = (p + r)/2; mergesort (A, p, q, CNT); mergesort (A, q + 1, R, CNT); merge (A, P, Q, R, CNT );} void output (int * a, int Len) {int I = 0; for (I = 0; I <Len; I ++) {printf ("% d ", A [I]);} printf ("\ n");} int main () {int I = 0; int K = 1; int CNT = 0; // calculate the number of Reverse Order pairs int A [buffer_size]; memset (A, 0, sizeof (a); srand (unsigned) Time (null )); for (I = 0; I <buffer_size; I ++) {A [I] = rand () % buffer_size;} printf ("randomly generated array :"); output (A, buffer_size); printf ("after Bubble Sorting:"); mergesort (A, 0, BUFFER_SIZE-1, & CNT); output (A, buffer_size ); printf ("Number of Reverse Order pairs: % d \ n", CNT); System ("pause"); Return 0 ;}