归并排序

归并排序是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。


归并排序的算法思想:
假设初始系列有n个待排序的记录,则可以看成n个有序的子序列,每个子序列长度为1;然后两两归并,得到n/2个长度为2的序列;再两两归并…….如此重复,直到得到一个长度为n的有序序列。
归并排序的时间复杂度:
时间复杂度为O(nlogn) 这是该算法中最好、最坏和平均的时间性能。
归并排序的空间复杂度:
空间复杂度为 O(n);归并排序比较占用内存,但却是一种效率高且稳定的算法。

下面举例子说明:
这里写图片描述

算法实现:

#include <stdlib.h>
#include <stdio.h>

void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
    int i = startIndex, j=midIndex+1, k = startIndex;
    for(;i<=midIndex&&j<=endIndex;k++){
        if(sourceArr[i]>=sourceArr[j]){
            tempArr[k]=sourceArr[j++];
        }else{
            tempArr[k]=sourceArr[i++];
        }
    }

    while(i<=midIndex){//将剩余的元素直接copy到tempArr中
        tempArr[k++]=sourceArr[i++];
    }
    while(j<=endIndex){
        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) / 2;
        MergeSort(sourceArr, tempArr, startIndex, midIndex);
        MergeSort(sourceArr, tempArr, midIndex+1, endIndex);
        Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
    }
}

int main()
{
    int a[8] = {50, 10, 20, 30, 70, 40, 80, 60};
    int i, b[8];
    MergeSort(a, b, 0, 7);
    for(i=0; i<8; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值