Combining the 51来 of "Jian-point offer (second edition)" to discuss merge sort

Source: Internet
Author: User
Tags cmath

I. Main TOPIC

Given an array a, for the two numbers in array a, if the preceding number is greater than (must be greater than, equal to, not counted) the number following, then these two numbers form an inverse pair. The total number of reverse pairs in the output array A is required. For example, for the array {7,5,6,4}, there are altogether 5 reverse pairs, namely (7,5), (7,6), (7,4), (5,4), (6,4).

Note: According to test instructions, it must be counted according to the relative order of the elements in the original array, given the array, then in what order.

Two. Analysis of Ideas

Method 1: Brute force. Double loops to determine all the inverse logarithm, the time complexity is O (n^2), the space complexity is O (1). A large amount of data must be timed out.

Method 2: Using the idea of merge sort, the concrete idea introduces the reference "Jian refers to offer". Since this reference to the idea of merging sorting, so here first to talk about the classic merge sort, and then on this basis to give the implementation of this topic.

1.2-Way Merge Sort implementation:

On the idea of merging sort, here is not much to say (book or online information a lot), here only to give a concrete implementation, counted as a template bar, the code is as follows:

#include <iostream> #include <unordered_map> #include <queue> #include <cstring> #include < cstdlib> #include <cmath> #include <algorithm> #include <sstream>using namespace std; #define Max_    LEN 1000int Temp[max_len] = {0};void Merge (int a[],int Low, int. Middle,int high) {int i = 0, j = 0, k = 0;    for (k = low, k <= High; k++) temp[k] = a[k]; for (i = low, J = middle + 1, k = i; I <= Middle && J <= High; k++)//Note the termination condition of I and J {if (Temp[i] <=        TEMP[J]) a[k] = temp[i++];    else a[k] = temp[j++];    } while (I <= middle) a[k++] = temp[i++]; while (J <= high) a[k++] = temp[j++];} void mergesort (int a[], int low, int. high) {if (a = = nullptr | | Low < 0 | | High <= 0)//special input and boundary condition judgment and processing Retu    Rn if (Low < high) {int middle = (high-low)/2 + low;//This is the median to prevent overflow mergesort (a,low,middle);//to split the array        Sub-mergesort (A,middle + 1,high); MeRge (A,low,middle,high);    Merges the split array}}int main () {int a[] = {2,1,3,4,6,5};    MergeSort (a,0,5);    for (int i = 0; i < 6; i++) cout<<a[i]; Cout<<endl;}

The results of the operation are as follows:

Among them, there are several points to note:

(1). The temp array is used to sort the auxiliary array A, the definition of this array is best written outside the merge function ( because the program calls the merge function multiple times, if it is defined in the merge function each time, it can cause memory overflow ), defined in the MergeSort function (at which point it needs to be passed as a parameter into the merge function) or as a global variable.

(2). Low and High is the subscript index of the array, and the 2-way merge is to divide the array into [low,middle] and [Middle + 1,high] two parts.

(3). The last two while loops in the merge function are to handle two different lengths of the array, leaving the extra portion directly assigned to the remainder of the array A.

2. The realization of the subject

Based on the implementation of the 2-way merge above, we can easily get the following code:

#include <iostream> #include <unordered_map> #include <queue> #include <cstring> #include < cstdlib> #include <cmath> #include <algorithm> #include <sstream>using namespace std; #define Max_  LEN 1000int Temp[max_len] = {0};static int cnt = 0;void Merge (int a[],int Low, int. Middle,int high) {int i = 0, j = 0,    k = 0;    for (k = low, k <= High; k++) temp[k] = a[k];            for (i = low, J = middle + 1, k = i; I <= Middle && J <= High; k++) {if (Temp[i] <= temp[j])        A[K] = temp[i++];            else {A[k] = temp[j++];        CNT = (cnt + middle-i + 1)% 1000000007;    }} while (I <= middle) a[k++] = temp[i++]; while (J <= high) a[k++] = temp[j++];}    void mergesort (int a[], int low, int. high) {if (a = = nullptr | | Low < 0 | | High <= 0) return;        if (Low < high) {int middle = (high-low)/2 + low;        MergeSort (A,low,middle); MeRgesort (A,middle + 1,high);    Merge (A,low,middle,high);    }}int Main () {int a[] = {2,1,3,4,6,5};    MergeSort (a,0,5);    for (int i = 0; i < 6; i++) cout<<a[i];    cout<<endl; Cout<<cnt<<endl;}

is actually a step on the basis of the 2-way merge sort: cnt = (cnt + mid-i + 1)% 1000000007

Equivalent in the process of merging to complete the inverse logarithm of the statistics, here because according to the requirements of the cattle on the practice, so CNT in the calculation process% of 1000000007, but the point to note is:

(1) It is used here

CNT = (cnt + mid-i + 1)% 1000000007

Instead of

CNT + = (mid-i + 1)% 1000000007

Realize that the implementation of the two formulations is different, the former is the whole of CNT to take the remainder, often do not overflow, and the latter is only to increase the partial residual, may occur overflow.

(2) So, why is Mid-i + 1 here? This is because in the process of merging, the actual statistic is the inverse logarithm between different arrays (or between different parts of the same array). (and the inverse logarithm of the inner of the array is a sub-problem of the problem; As long as the inverse logarithm between the different arrays is solved, it is possible to solve the inverse logarithm in the array, in more detail, see the "Jian"); the 2-way merge sort, when the two arrays are first merged, The two arrays are already ordered (here in ascending order), so if temp[i]>temp[j], it means that all the elements from position I to position middle are greater than temp[j], so that total and increase middle-i + 1.

(3) In addition, there is a point to note, that is, if there are equal elements in the array, and is less than the case, so when Temp[i] <= temp[j] is not counted as reverse.

The time complexity of the method is O (N*logn), the space complexity is O (N), and compared with Method 1, it also belongs to a spatial time-change strategy.

Combining the 51来 of "Jian-point offer (second edition)" to discuss merge sort

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.