归并排序算法C++的实现

#include <iostream>
using namespace std;

void merge(int a[], int first, int mid, int last, int c[])
{
    int i = first,j = mid + 1; 
    int m = mid, n = last;
    // k 的值与 i的值必须相等,要不无法把c的值回写给a
    int k = first;
    //都还没有到数组的头
    while (i<=m && j<=n)
    {
        if (a[i] <=  a[j])
        {
            //新数组加插入较小的元素
            c[k++] = a[i++];
        }
        else
        {
            c[k++] = a[j++];
        }
    }

    //如果i的部分还没有完全插入到数组就将剩余部分加入
    if (i <= m) {
        while (i<=m)
            c[k++] = a[i++];
    }

    if (j <= n) {
        while (j<=n)
            c[k++] = a[j++];
    }
    //回写数据给a,如果不回写,a就永远不会被排序
    for(int i=first;i<=last;i++)
        a[i] = c[i];
}

void mergeSort(int a[], int first, int last,  int temp[])
{
    if (first < last)
    {
        int mid = (last + first) / 2;
        mergeSort(a, first, mid, temp);
        mergeSort(a, mid+1, last, temp);
        merge(a, first, mid, last, temp);
    }
}

int main()
{
    int a[] = {3, 20, 32, 90, 23, 41, 5, 3, 6, 4, 7, 5, 7, 4};
    int b[sizeof(a) / sizeof(*a)];
    mergeSort(a, 0, sizeof(a) / sizeof(*a), b);

    //output
    for(int i=0; i<sizeof(a) / sizeof(*a); i++)
        cout << b[i] << ' ';
    cout << endl;

    return 0;
}


参考:

http://baike.baidu.com/view/90797.htm

http://zh.wikipedia.org/wiki/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F

http://blog.csdn.net/morewindows/article/details/6678165

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值