| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1183 人关注过本帖
标题:求二路归并排序算法的非递归实现
只看楼主 加入收藏
小小哥
Rank: 4
等 级:业余侠客
帖 子:139
专家分:224
注 册:2010-11-28
结帖率:75%
收藏
 问题点数:0 回复次数:2 
求二路归并排序算法的非递归实现
求二路归并排序算法的非递归实现,一点思路都没有,求高手指点~
搜索更多相关主题的帖子: 递归 算法 
2010-12-21 19:20
小小哥
Rank: 4
等 级:业余侠客
帖 子:139
专家分:224
注 册:2010-11-28
收藏
得分:0 
还是我自己来解答吧……
程序代码:
void mergeImproved( vector<Comparable> &a )
{
    int size = a.size();
    vector<Comparable> b( size );  // 唯一的临时数组
    int maxLayer = 1;
    for ( int items = 2; items < size; items *= 2, ++maxLayer );

    // for each layer, perform merge sort.
    for ( int curLayer = 0, items = 0; curLayer < maxLayer; ++curLayer )
    {
        items = int( pow( double( 2 ), double( curLayer ) ) );//功能:pow(x,y)返回x的y次幂

        // decide which array of a and b is input or output
        vector<Comparable> &in = ( curLayer % 2 == 0 ) ? a : b;
        vector<Comparable> &out = ( curLayer % 2 == 0 ) ? b : a;
        
        // for each left and right sub arrays on the block
        for ( int index = 0; index < size; index += ( 2 * items ) ) 
        {

            // fix the left array's first and last indices
            int first1 = index;
            int last1 = ( first1 + items - 1 < size - 1 ) ? first1 + items - 1 : size - 1;

            // fix the right array's first and last indices
            int first2 = ( last1 + 1 < size - 1 ) ? last1 + 1 : size - 1;
            int last2 = (first2 + items - 1 < size - 1 ) ? first2 + items - 1 : size - 1;

            // now merge them in one block
            int outIx = first1;
            for ( ; first1 <= last1 && first2 <= last2; ++outIx )
                out[outIx] = ( in[first1] < in[first2] ) ? in[first1++] : in[first2++];

            for ( ; first1 <= last1; ++first1, ++outIx )
                out[outIx] = in[first1];

            for ( ; first2 <= last2; ++first2, ++outIx )
                out[outIx] = in[first2];
        }
    }

    // in case the sort items are in the temporary array
    if ( maxLayer % 2 == 1 )
        a = b; // copy them back to the original
}
2010-12-22 09:56
小小哥
Rank: 4
等 级:业余侠客
帖 子:139
专家分:224
注 册:2010-11-28
收藏
得分:0 
ps:以上代码经验证有点小错误,有数组越界问题,改正如下:
  int first2 = ( last1 + 1 < size - 1 ) ? last1 + 1 : size - 1;

改为:
  int first2 = ( last1 + 1 < size - 1 ) ? last1 + 1 : size;


2010-12-23 18:21
快速回复:求二路归并排序算法的非递归实现
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014928 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved