归并排序 MergeSort函数里if(pSrc!=R)语句删了运行结果出错,但我不太理解这个条件的作用是什么
template<class T>
void Merge(T* pSrc, T* pDst, int low, int mid, int high)合并
{
int i = low, j = mid + 1, k = low;
while (i <= mid && j <= high)
{
if (pSrc[i] <= pSrc[j])
{
pDst[k] = pSrc[i];
i++;
}
else
{
pDst[k] = pSrc[j];
j++;
}
k++;
}
while (i <= mid)
{
pDst[k] = pSrc[i];
i++;
k++;
}
while (j <= high)
{
pDst[k] = pSrc[j];
j++;
k++;
}
}
template<class T>
void MergePass(T* pSrc, T* pDst, int nsize, int nLength)
{
int i, j;
for (i = 0; (i + 2) * nLength < nsize; i+=2)
Merge(pSrc, pDst, i * nLength , (i + 1) * nLength-1, (i + 2) * nLength-1);
if ((i + 1) * nLength < nsize)
Merge(pSrc, pDst, i * nLength , (i + 1) * nLength-1, nsize-1);
else
{
for (j = i * nLength ; j <=nsize; j++)
pDst[j] = pSrc[j];
}
}
template<class T>
void MergeSort(T R[], int nSize)
{
int nLength;
T* MR = new T[nSize + 1];
T* pSrc = R, * pDst = MR, * p;
int i;
if (MR == NULL)
exit(1);
for (nLength = 1; nLength < nSize; nLength *= 2)
{
MergePass(pSrc, pDst, nSize, nLength);
p = pSrc;
pSrc =pDst;
pDst = p;
}
if (pSrc != R)
{
for (i = 0; i < nSize; i++)
R[i] = MR[i];
}
delete[]MR;
}
int main()
{
int A[] = {43,56,37,28,17,37,22,30,2 };
MergeSort(A, 9);
for(int i=0;i<9;i++)
cout<<A[i]<<',';
return 0;
}
删除if后运行会显示MR为未初始化的内存,麻烦能帮我看看