数据结构学习——归并排序(C语言实现)

归并排序原理

基于分而治之思想,递归地把待排序序列分解为若干子序列并进行排序,再把已排序的子序列合并为整体有序序列,最终实现全序列的有序。

归并操作

归并操作,也叫归并算法,指的是将两个顺序序列合并成一个顺序序列的方法。
如 设有数列{8,3,2,9,7,1,5,4}
初始状态:8,3,2,9,7,1,5,4
在这里插入图片描述

c语言实现

merge函数的实现

void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
    int i = startIndex, j=midIndex+1, k = startIndex;
    //首先将小的放在前面
    while(i!=midIndex+1 && j!=endIndex+1)
    {
        if(sourceArr[i] > sourceArr[j])//如果前半部分比后半部分大,就将小的放在前面
            tempArr[k++] = sourceArr[j++];
        else
            tempArr[k++] = sourceArr[i++];
    }
    while(i != midIndex+1)
        tempArr[k++] = sourceArr[i++];//小的放在前面
    while(j != endIndex+1)
        tempArr[k++] = sourceArr[j++];
    for(i=startIndex; i<=endIndex; i++)
        sourceArr[i] = tempArr[i];
}

递归实现归并排序

void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex)
{
    int midIndex;
    if(startIndex < endIndex)
    {
        midIndex = startIndex + (endIndex-startIndex) / 2;//避免溢出int
        MergeSort(sourceArr, tempArr, startIndex, midIndex);
        MergeSort(sourceArr, tempArr, midIndex+1, endIndex);
        Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
    }
}

主函数测试

int main()
{
    int test[] = {1,2,5,6,7,8,4,2,3,4,1,2,3};
    int n = (int)(sizeof(test)/sizeof(test[0]));
    int a[13];
    //printf("%d\n", (int)(sizeof(test)/sizeof(test[0])));
    MergeSort(test,a,0,n - 1);
    int i;
    for(i = 0;i < sizeof(test)/sizeof(test[0]);i++)
        printf("%d ",test[i]);
    return 0;
}

输出

1 1 2 2 2 3 3 4 4 5 6 7 8
Process returned 0 (0x0)   execution time : 0.699 s
Press any key to continue.

算法分析

时间复杂度O(nlogn)
空间复杂度就是那个临时的数组和递归时压入栈的数据占用的空间:n + logn;所以空间复杂度为: O(n)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的算算

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值