排序(四)之归并排序

简单描述

这个算法合并的是两个已排序的表
步骤:
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!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值