归并排序—自底向上和自顶向下

今天花了一些时间看了买来很久的《编程珠矶》,第一章看了一些,就感觉为啥大二的时候没买这本书,或者买来很久了为啥没看。这本书真的很好,第一章以一个磁盘文件排序的问题为切入点,引入了磁盘文件的多路归并排序,多通道的排序,还引入了位图的概念,类似于C++中的bitset,减少内存空间的占用。很长时间没写过排序算法了,简单实现了归并排序,位图算法的排序比较简单,进行HASH 映射即可。

void merge(int *p1_start, int *p2_start, int *end,int *copy) 
{
    int *p1 = p1_start;
    int *p2 = p2_start;
    int count =0;
    while(p1 < p2_start && p2 < end)
    {
        if(*p1 <= *p2)
            copy[count++] = *p1++;
        else 
            copy[count++] = *p2++;
    }
    while(p1 < p2_start)
        copy[count++] = *p1++;

    while(p2 < end)
        copy[count++] = *p2++;

    int i;
    for(i = 0;i< count;i++)
        p1_start[i] = copy[i];
}

/*
 * from bottom  to top
 */
void merge_sort(int *begin, int *end, int *copy)
{
    int len = end -begin;
    int step,j;
    for( step = 1;step < len ;step<<=1)
    {
        for (j = 0; (j+1)*step <= len; j+=2)
        {
            merge(begin+j*step,begin+(j+1)*step,begin+(j+2)*step,copy);
        }
    }
}

/**
 * from top to bottom
 */
void merge_sort(int *begin, int *end, int *copy)
{
    if(end - begin == 1)
        return ;
    int len = end - begin;
    merge_sort(begin,begin+len/2,copy);
    merge_sort(begin+len/2,copy);
    merge(begin,begin+len/2,end,copy);
}

转载于:https://www.cnblogs.com/lonelycatcher/archive/2012/07/11/2586883.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值