Given an integer array, if an element value with a lower value is smaller than a lower value, it is called a reverse order.

Source: Internet
Author: User

[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]



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.