首页 > 代码库 > 分治法

分治法

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

 

分治法