#include<iostream>
#include<vector>
using namespace std;
void Merge(int *a, int nLeft, int nMid, int nRight)
{
int nL = nLeft;
int nM = nMid + 1;
int nR = nRight;
int i = 0;
int *b = new int[nRight - nLeft + 1];
while (nL <= nMid && nM <= nR)
{
if (a[nL] < a[nM])
{
b[i] = a[nL];
i++;
nL++;
}
else
{
b[i] = a[nM];
nM++;
i++;
}
}
while (nL<=nMid)
{
b[i] = a[nL];
i++;
nL++;
}
while (nM <= nR)
{
b[i] = a[nM];
nM++;
i++;
}
for (int j = 0; j < i; j++)
{
a[nLeft + j] = b[j];
}
delete[] b;
}
void MergeSort(int *a, int nLeft, int nRight)
{
if (nLeft >= nRight)
{
return;
}
int nMid = (nLeft + nRight) * 0.5;
MergeSort(a, nLeft, nMid);
MergeSort(a, nMid + 1, nRight);
Merge(a, nLeft, nMid, nRight);
}
int main()
{
int a[] = {1,5,9,8,7,4,6,3,1};
int nSize = sizeof a / sizeof a[0];
MergeSort(a, 0, nSize - 1);
for (int i = 0; i < nSize; i++)
{
cout << a[i] << ends;
}
cout << endl;
system("pause");
}