/*归并排序是利用归并的思想,采用分治策略,将问题分为一些小问题然后递归求解。在治阶段将分阶段得到****的各答案合在一起。比如一个{8,4,5,7,1,3,6,2}的数列分成{8,4,5,7}和{1,3,6,2}之后
****再分成{8,4},{5,7},{1,3},{6,2}再分成{8}{4}{5}{7}{1}{3}{6}{2},然后开始比较先比较8,4
****小的放前面之后合并,{4,8},以此类推合并{5,7},{1,3},{2,6}再比较合并{4,5,7,8},{1,****2,3,6},再比较合并{1,2,3,4,5,6,7,8}.
****归并是稳定排序,时间复杂度nlogn。
*/
#include <stdio.h>
#include<malloc.h>
//using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//template<class Type>
//合并
void Merge(int A[], int TmpAry[], int Lpos, int Rpos, int RightEnd)
{
int i, LeftEnd, NumTypes, TmpPos;
LeftEnd = Rpos - 1;
TmpPos = Lpos; //临时数组指针
NumTypes = RightEnd - Lpos + 1;
while (Lpos <= LeftEnd&&Rpos <= RightEnd)
{
if (A[Lpos] <= A[Rpos])
{
TmpAry[TmpPos++] = A[Lpos++];
}
else
{
TmpAry[TmpPos++] = A[Rpos++];
}
}
while (Lpos <= LeftEnd)
{
TmpAry[TmpPos++] = A[Lpos++];
}
while (Rpos <= RightEnd)
{
TmpAry[TmpPos++] = A[Rpos++];
}
//复制
for (i = 0; i<NumTypes; i++, RightEnd--)
A[RightEnd] = TmpAry[RightEnd];
}
void MSort(int A[], int TmpAry[], int left, int right)
{
if (left<right)
{
int center = (left + right) / 2;
MSort(A, TmpAry, left, center);//处理左半部
MSort(A, TmpAry, center + 1, right);//处理右半部分
Merge(A, TmpAry, left, center + 1, right);//合并
}
}
//测试
void MergeSort(int A[], int N)
{
int *TmpAry;
TmpAry = (int*)malloc(N*sizeof(int));
if (TmpAry != NULL)
{
MSort(A, TmpAry, 0, N - 1);
free(TmpAry);
}
else
printf("ERROR");
//cout<<"not space for tem array!"<<endl;
}
int main(int argc, char *argv[]) {
int i;
int A[8] = { 6,3, 1, 2, 12, 32,16,89 };
MergeSort(A, 8);
for (i = 0; i<8; i++)
//cout<<A[i]<<endl;
printf("%d\n", A[i]);
return 0;
}