简单描述
这个算法合并的是两个已排序的表
步骤:
1. 取两个输入数组 A 和 B,一个输出数组 C,以及三个计数器 Aptr,Bptr,Cptr,它们初始置于对应数组的开端。
2. A[Aptr] 和 B[Bptr] 中的较小者被拷贝到 C 中的下一个位置,相关的计数器向前推进一步。
3. 当两个输入表有一个用完的时候,则将另一个表中剩余部分拷贝到 C 中。
该算法是经典的分治策略
void merge(ElementType arr[], ElementType tmpArr[], int Lpos, int Rpos, int rightEnd)
{
int i, leftEnd, numElements, tmpPos;
leftEnd = Rpos - 1;
tmpPos = Lpos;
numElements = rightEnd - Lpos + 1;
while(Lpos <= leftEnd && Rpos <= rightEnd)
{
if(arr[Lpos] <= arr[Rpos])
{
tmpArr[tmpPos++] = arr[Lpos++];
}
else
{
tmpArr[tmpPos++] = arr[Rpos++];
}
}
while(Lpos <= leftEnd)//copy rest of first half
{
tmpArr[tmpPos++] = arr[Lpos++];
}
while(Rpos <= rightEnd)//copy rest of second half
{
tmpArr[tmpPos++] = arr[Rpos++];
}
for(i = 0; i < numElements; i++,rightEnd--)//copy tmpArr back
{
arr[rightEnd] = tmpArr[rightEnd];
}
}
void MSort(ElementType arr[], ElementType tmpArr[], int left, int right)
{
int center;
if(left < right)
{
center = (left + right) / 2;
MSort(arr, tmpArr, left, center);
MSort(arr, tmpArr, center + 1, right);
merge(arr, tmpArr,left, center + 1, right);
}
}
void mergeSort(ElementType arr[], int n)
{
ElementType *tmpArr;
tmpArr = malloc(n * sizeof(ElementType));
if(tmpArr != NULL)
{
MSort(arr, tmpArr, 0, N - 1);
free(tmpArr);
}
else
{
Error("No space for tmpArr!");
}
}