### 归并排序Merge sort

``` 1 //将有序数组a[]和b[]合并到c[]中
2 void MemeryArray(int a[], int n, int b[], int m, int c[])
3 {
4     int i, j, k;
5
6     i = j = k = 0;
7     while (i < n && j < m)
8     {
9         if (a[i] < b[j])
10             c[k++] = a[i++];
11         else
12             c[k++] = b[j++];
13     }
14
15     while (i < n)
16         c[k++] = a[i++];
17
18     while (j < m)
19         c[k++] = b[j++];
20 }```

``` 1 //将有二个有序数列a[first...mid]和a[mid...last]合并。
2 void mergearray(int a[], int first, int mid, int last, int temp[])
3 {
4     int i = first, j = mid + 1;
5     int m = mid,   n = last;
6     int k = 0;
7
8     while (i <= m && j <= n)
9     {
10         if (a[i] <= a[j])
11             temp[k++] = a[i++];
12         else
13             temp[k++] = a[j++];
14     }
15
16     while (i <= m)
17         temp[k++] = a[i++];
18
19     while (j <= n)
20         temp[k++] = a[j++];
21
22     for (i = 0; i < k; i++)
23         a[first + i] = temp[i];
24 }
25 void mergesort(int a[], int first, int last, int temp[])　　　　　　　　//这里用递归实现归并排序
26 {
27     if (first < last)
28     {
29         int mid = (first + last) / 2;
30         mergesort(a, first, mid, temp);    //左边有序
31         mergesort(a, mid + 1, last, temp); //右边有序
32         mergearray(a, first, mid, last, temp); //再将二个有序数列合并
33     }
34 }
35
36 bool MergeSort(int a[], int n)
37 {
38     int *p = new int[n];
39     if (p == NULL)
40         return false;
41     mergesort(a, 0, n - 1, p);
42     delete[] p;
43     return true;
44 }```
```/*归并排序的效率是比较高的，设数列长为N，将数列分开成小数列一共要logN步，每步都是一个合并有序数列的过程，时间复杂度可以记为O(N)，故一共为O(N*logN)。因为归并排序每次都是在相邻的数据中进行操作，所以归并排序在O(N*logN)的几种排序方法（快速排序，归并排序，希尔排序，堆排序）也是效率比较高的。
*/

//算法导论 上的 合并排序

#include<iostream>
#include<stdlib.h>

using namespace std;

void Merge(int* A, int p, int q, int r)
{
int i,j,k;
int n1 = q - p + 1;
int n2 = r - q;

int* L = (int*)malloc(sizeof(int)*(n1+2));
int* R = (int*)malloc(sizeof(int)*(n2+2));

for(i=1;i<=n1;i++)
{
L[i] = A[p+i-1];
}
for(j=1;j<=n2;j++)
{
R[j] = A[q+j];
}
L[n1+1] = 0x7FFFFFFF;
R[n2+1] = 0x7FFFFFFF;

i = 1;
j = 1;
for(k=p;k<=r;k++)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
}
}

void MergeSort(int* A, int p, int r)
{
if(p < r)
{
int q = (p+r)/2;
MergeSort(A,p,q);
MergeSort(A,q+1,r);
Merge(A,p,q,r);
}
}

int main()
{
int a[10] = {214,3636,22,55,37,45,12,54,264,52};
MergeSort(a,0,9);

for(int i=0;i<10;i++)
{
printf("%d ",a[i]);
}
printf("\n");

return 0;
}```