C + + Programming: C + + merge sort implementation (Introduction to algorithm)

Source: Internet
Author: User
Tags printf sort

The subscript on the introduction of the algorithm starts from 1, but in order to be consistent with the design idea of the C + + STL, the realization of all functions is unified with left-right open interval. In the middle of a lot of changes, because the subscript modification is not easy to get rid of, you need to always maintain the cycle invariant, a slight error will make the result of some errors.

#include

#include

#include

#include

using namespace Std;

void merge (int *a, int p, int q, int r) {//merge [P, R), left close right open interval

int n1 = q-p, N2 = R-q; Note that the number of changes in the book and the difference between the use of left-right open interval is the advantage of a uniform number of form representation

int *l = new Int[n1], *r = new INT[N2];

for (int i = 0; i < N1 ++i)//l[0, N1) <== a[p, q)

L[i] = A[p+i];

for (int i = 0; i < n2 ++i)//r[0, N2) <== a[q, R)

R[i] = A[q+i]; It's not q+i+1 here.

int i = 0, j = 0;

int k = p;

while (I < N1 && J < N2) {

if (L[i] <= r[j])

a[k++] = l[i++];

Else

a[k++] = r[j++];

}

while (I < N1)//due to the absence of Sentinels, additional elements need to be added

a[k++] = l[i++];

while (J < N2)

a[k++] = r[j++];

delete [] L;

delete [] R;

}

void Merge_sort (int *a, int p, int r) {//Call interface Merge_sort (A, 0, Len), not (a, 0, len-1)

if (P < r-1) {//At this time is not P < R, left closed right open interval when p>=r-1, the child array at most one element

int q = p + (r-p)/2;

Merge_sort (A, p, q);

Merge_sort (A, q, R); Note that the interface is unified, this is not (a, q+1, R) but (a, q, R), the benefits of left-right open

Merge (A, p, Q, R);

}

}

int main ()

{

Srand (Time (NULL));

int n;

while (CIN "n") {

int a[n];

for (int i = 0; i < n; ++i)

A[i] = rand ()% n;

for (int i = 0; i < n; ++i)

printf ("%d", a[i]);

printf ("n");

Merge_sort (A, 0, N);

for (int i = 0; i < n; ++i)

printf ("%d", a[i]);

printf ("n");

}

}

Finally, using tens of thousands of sets of test data, the results are similar to the STL in the sort results, the basic description of the code is correct.

Related Keywords:
Related Article E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD