归并排序
步骤:
1.分解
2.解决
3.合并
#include<iostream>
using namespace std;
void Merge(int* a, int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int* L = new int[n1 + 1];
int* R = new int[n2 + 1];
for (int i = 0; i < n1; i++)
{
L[i] = a[p + i];
}
for (int j = 0; j < n2; j++)
{
R[j] = a[q + j + 1];
}
L[n1] = 1111;
R[n2] = 1111;
int i = 0, j = 0;
for (int k = p; k <= r; k++)
{
if (L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
}
delete[]L;
delete[]R;
}
void MergeSort(int* a, int l, int r)
{
if (l < r)
{
int m = (l + r) / 2;
MergeSort(a, l, m);
MergeSort(a, m + 1, r);
Merge(a, l, m, r);
}
}
int main()
{
int a[10] = { 5,2,4,1,8,9,10,12,3,6 };
for (int i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
MergeSort(a, 0, 9);
for (int i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}