Recursive O (NLGN) solves reverse order number

Source: Internet
Author: User

Introduction

The first time I learned that the reverse number is in the Advanced Algebra course. When I wanted to calculate the inverse number of a sequence, intuition was solved by the double cyclic O (n^2) violence. Now gradually the merging algorithm has a certain understanding, so decided to use C + + code to try sledgehammer.

Introduction to reverse order number

1 , 2 n n rank (for short), or general, n A separate element is a column called "A n rank ". For example, 1234 and 4312 4 24315 is a 5 rank.

In an n -level arrangement, if the front and back positions of a pair of numbers are opposite to the size order, that is, the previous number is greater than the subsequent number, then they are called an "inverse".

Example:
   1,2,3,4become the natural permutation number for0
   3,2,4,1a number of columns in reverse order have(3,2) (3,1) (2,1) (4,1)so the reverse number is4

Code implementation

#include <cstdio>#include<cstring>Const intN =4;//to test the size of an arrayintCnt//Global Variables voidMergeSort (int*a,intPintQint*T) {    if(p+1&GT;=Q)return; intm=p+ (Q-P)/2;    MergeSort (a,p,m,t);    MergeSort (a,m,q,t); //Merge     for(intx=p,y=m,i=p;i<q;i++){        if(X<m&&y<q&&a[x]<a[y] | | y>=q) T[i]=a[x++];//go to ' left ' plus        Else{T[i]= a[y++]; CNT+ = (m-x);//The emphasis here is to add a number to the right, and the number of elements to the left that have not been added to T        }    }     for(inti=p;i<q;i++) A[i]=t[i];}intMain () {intT[n];//auxiliary Array, which is the extra Space cost O (N)    inta[]={3,2,4,1}; CNT=0;//initial CNT is 0MergeSort (A,0, n,t); printf ("Number of reverse order:%d\n", CNT); return 0;}

Conclusion

Compared with the previous double cyclic violence method, we can prove that the time complexity of merging solution is O (NLGN). Therefore, when N is large, it can be found that this merging algorithm is significantly more efficient.

Recursive O (NLGN) solves reverse order number

Related Article

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.