首页 > 其他 > 详细

分治法

时间:2016-11-05 11:48:21      阅读:285      评论:0      收藏:0      [点我收藏+]

1)归并排序

 

//Merge sort
template<typename T>
list<T> mergeSort(const list<T>& source);

template<typename T>
list<T> mergeSort(const list<T>& source)
{
    list<T> ret;

    if(source.size()==1)
    {
        ret=source;
    }
    else if(source.size()==2)
    {
        typename list<T>::const_iterator firstit=source.begin();
        T firstvalue=*firstit;
        typename list<T>::const_iterator secondit=++firstit;
        T secondvalue=*secondit;

        if(firstvalue<=secondvalue)
        {
            ret=source;
        }
        else
        {
            ret.push_back(secondvalue);
            ret.push_back(firstvalue);
        }

    }
    else
    {
        unsigned int count_list=source.size();
        unsigned int modN= count_list%2;
        unsigned int subret=count_list/2;

        typename list<T>::const_iterator it=source.begin();

        list<T> leftS;
        list<T> rightS;

        for(int i=0;i!=subret+modN;++i)
        {
            leftS.push_back(*it);
            ++it;
        }

        for(int i=0;i!=subret;++i)
        {
            rightS.push_back(*it);
            ++it;
        }

        leftS=mergeSort(leftS);//lefts 传递const 引用,效率和安全,不会改动.返回对象.lefts被copy赋值函数处理.
        rightS=mergeSort(rightS);

        typename list<T>::const_iterator lefttop=leftS.begin();
        typename list<T>::const_iterator righttop=rightS.begin();

        while(lefttop!=leftS.end() || righttop!=rightS.end())
        {
            // check each top
            if(*lefttop<=*righttop)
            {
                ret.push_back(*lefttop);
                ++lefttop;
            }
            else
            {
                ret.push_back(*righttop);
                ++righttop;
            }
        }
        if(lefttop!=leftS.end())
        {
            //push no process data
            for(lefttop;lefttop!=leftS.end();++lefttop)
            {
                ret.push_back(*lefttop);
            }
        }
        else if(righttop!=rightS.end())
        {
            for(righttop;righttop!=rightS.end();++righttop)
            {
                ret.push_back(*righttop);
            }
        }
        return ret;
    }



    return ret;
}

 

分治法

原文:http://www.cnblogs.com/lsfv/p/6032527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!