Merge sort typical divide and conquer strategy embodiment, time complexity is O (NLGN), spatial complexity is O (n). is a stable sort.
The following is the C language implementation code.
#define MAX 10000000//p, Q, R is the subscript void merge of the elements (int a[], int p, int q, int r) { int n1 = q-p + 1; int n2 = r-q; int * L = (int *) malloc (sizeof (int) * n1 + 1); int * R = (int *) malloc (sizeof (int) * n2 + 1); int I, j, K; for (i = 0; i < N1; i++) { L[i] = a[p + i]; } for (j = 0; J < N2; J + +) { R[j] = a[q + j + 1]; } L[i] = MAX; R[J] = MAX; i = 0; j = 0; for (k = p; k <= R; k++) { if (L[i] <= r[j]) { a[k] = l[i]; i++; } else { A[k] = r[j]; j + +;}} } void Merge_sort (int a[], int p, int r) { if (P < r) { int q = (p + r)/2; Merge_sort (A, p, q); Merge_sort (A, q + 1, r); Merge (A, p, Q, R);} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Merge sort C language implementation