Merge sort-Calculate reverse order number

Source: Internet
Author: User

Merge sort-Calculate reverse order number

Merge sort uses the thought of divide and conquer, Time complexity O (N*LOGN) dynamic memory utilization can reduce the space overhead;

Merge sort can also be used to calculate reverse order number;

Number of reverse order: a pair of numbers opposite the position and size in the sequence;

Number of reverse order = number of adjacent two digits exchanged in bubble sort;

intA[maxn],n;Long LongAns//The reverse number is generally very large, with a long longvoidCompute_ans (int*a,intBeginintMidintend) {    intlen_l=mid-begin+1; intlen_r=end-mid; int*left=New int[len_l+1];//Space Saving    int*right=New int[len_r+1];  for(intI=0; i<len_l;i++) left[i]=a[begin+i];  for(intI=0; i<len_r;i++) right[i]=a[mid+1+i]; Left[len_l]=right[len_r]=inf;//precautions against cross-border    inti,j;i=j=0;  for(intk=begin;k<=end;k++){        if(Left[i]<=right[j]) a[k]=left[i++]; Else{A[k]=right[j++]; Ans+=len_l-i;//calculates the number of reverse order, if only sort, the row is deleted; Reverse order = bubble Sort Interchange operation number}} delete left; //Remember to release, if not released will cause the MLEdelete right;}voidMergeSort (int*a,intBeginintend) {    if(begin<end) {        intMid= (begin+end)/2;        MergeSort (A,begin,mid); MergeSort (A,mid+1, end);    Compute_ans (A,begin,mid,end); }}intMain () { while(cin>>n,n) {ans=0;  for(intI=0; i<n;i++) cin>>A[i]; MergeSort (A,0, N-1); cout<<ans<<Endl; }    return 0;}
Merge Sort-Calculates the number of reverse orders

Merge sort-Calculate 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.