# Chapter 2 "Reverse Order Number of pairs" (Question 2-4)

Source: Internet
Author: User

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 ;}`

Related Keywords:

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.