void merger(int *A,int p, int q, int r)
{
int nLeft = q-p+1;
int nRight = r-q;
int i,j,k;
int *pLeft = (int *)malloc(sizeof(int)*(nLeft+1));
int *pRight = (int *)malloc(sizeof(int)*(nRight+1));
for (i = 0; i<nLeft; i++)
{
*(pLeft+i) = *(A+p+i);
}
*(pLeft+nLeft) = INT_MAX;
for (i = 0; i<nRight; i++)
{
*(pRight+i) = *(A+q+i+1);
}
*(pRight+nRight) = INT_MAX;
i = 0; j = 0;
for (k=p; k<=r;k++)
{
if (*(pLeft+i)<*(pRight+j))
{
*(A+k) = *(pLeft+i);
i++;
}
else
{
*(A+k) = *(pRight+j);
j++;
}
}
free(pLeft);
free(pRight);
}
void merge_sort(int *A,int p, int r)//A为待排数组指针,p为起始编号,r为结尾编号
{
if (p<r)
{
int q = (p+r)/2;
merge_sort(A,p,q);
merge_sort(A,q+1,r);
merger(A,p,q,r);
}
}
归并排序
最新推荐文章于 2024-08-12 19:32:44 发布