Problem
Find out the number of reverse order
Given an integer array, the value of an element with a large subscript value in the array is less than the value of an element whose subscript value is smaller than it, which is called an inverse order. i.e.: array a[]; For i < J and A[i] > A[j], this is called an inverse order. Given an array, it is required to write a function that calculates the number of all the reverse order in the array.
"Code"
#include <stdio.h> #include <stdlib.h> #include <string.h>int sumnum = 0;void merge (int *a, int *b, int be gin, 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 to}}while (I <= mid) b[k++] = A[i++];while (J <= E nd) b[k++] = a[j++];for (i = 0; i < K; i + +) A[i + begin] = B[i];} void mergesort (int *a, int *b, int begin, int end)//merge 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, be Gin, mid, End);}} int countreverse (int *a, int len)//Traversal lookup reverse 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, ten, 11};int len = sizeof (a)/sizeof (int), int *b;b = (int *) Mallo C (len * sizeof (int)); count = Countreverse (A, Len); MergeSort (A, B, 0, len-1);p rintf ("%d\n", Sumnum);p rintf ("%d\n", Count) ; free (b); return 0;}
"Execution Results"
Given an array of integers, if an element with a large subscript value in the array is less than the value of an element whose subscript value is smaller than it, it is called an inverse