码迷,mamicode.com
首页 > 其他好文 > 详细

分治法

时间:2016-11-05 11:50:41      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:back   span   merge   for   typename   source   top   sign   second   

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;
}

 

分治法

标签:back   span   merge   for   typename   source   top   sign   second   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!