[Problem]
Find the number of reverse orders
Given an integer array, if an element value with a lower value is smaller than a lower value, it is called a reverse order. That is, array a []. For I <j and a [I]> A [J], this is called an inverse order. Given an array, you need to write a function to calculate the number of all reverse orders in this array.
[Code]
# Include <stdio. h> # include <stdlib. h> # include <string. h> int sumnum = 0; void Merge (int * a, int * B, int begin, int mid, int end) {int I, j, k = 0; I = begin; j = Mid + 1; while (I <= Mid & J <= END) {if (a [I] <A [J]) B [k ++] = A [I ++]; else {B [k ++] = A [J ++]; sumnum + = mid-I + 1; // calculate reverse order pair} while (I <= mid) B [k ++] = A [I ++]; while (j <= end) B [k ++] = A [J ++]; for (I = 0; I <K; I ++) A [I + begin] = B [I];} void mergeso RT (int * a, int * B, int begin, int end) // merge and sort, time complexity O (N * lgn ). {Int mid = (begin + end)/2; If (begin <End) {mergesort (a, B, begin, mid); mergesort (a, B, Mid + 1, end); merge (a, B, begin, mid, end) ;}} int countreverse (int * a, int Len) // traverses the reverse query order, time complexity O (N ^ 2 ). {Int COUNT = 0; int I, j; for (I = 0; I <len-1; I ++) for (j = I + 1; j <Len; j ++) if (a [I]> A [J]) Count ++; return count;} int main (void) {int count; int A [] = {7, 4, 5, 3, 8, 6, 9, 10, 11}; int Len = sizeof (a)/sizeof (INT ); int * B; B = (int *) malloc (LEN * sizeof (INT); Count = countreverse (A, Len); mergesort (a, B, 0, len-1); printf ("% d \ n", sumnum); printf ("% d \ n", count); free (B); Return 0 ;}
[Running result]