zoukankan      html  css  js  c++  java
  • 合并排序(非哨兵方法)

    //subMerge2----非哨兵方法实现两个有序序列的合并
    template<typename T>
    void subMerge2(vector<T> &array,
    typename vector<T>::iterator iterBegin,
    typename vector<T>::iterator iterBarrier,
    typename vector<T>::iterator iterEnd)
    {
    //创建两个数组,分别存放以iterBarrier为界线的array的左边部分和右边部分
    vector<T> arrayLeft(iterBegin, iterBarrier+1);
    vector<T> arrayRight(iterBarrier+1, iterEnd);

    //定义分别指向两个数组的迭代器
    typename vector<T>::iterator iterLeft = arrayLeft.begin();
    typename vector<T>::iterator iterRight = arrayRight.begin();

    //定义指向原数组array的迭代器
    typename vector<T>::iterator iterArray = iterBegin;

    //只要其中一个数组为空则跳出循环
    while(iterLeft!=arrayLeft.end() && iterRight!=arrayRight.end())
    {
    if(*iterLeft < *iterRight) //如果左边小,将左边的值放入原数组
    {
    *iterArray = *iterLeft;
    ++iterLeft;
    ++iterArray;
    }
    else //如果右边小,将右边的值放入原数组
    {
    *iterArray = *iterRight;
    ++iterRight;
    ++iterArray;
    }
    }
    //左边为空
    if(iterLeft==arrayLeft.end())
    {
    //将右边剩下的数据复制到原数组
    //array.erase(iterArray, iterEnd);
    //array.insert(iterArray, iterRight, arrayRight.end());
    while(iterRight != arrayRight.end())
    {
    *iterArray = *iterRight;
    ++iterRight;
    ++iterArray;
    }
    }
    //右边为空
    if(iterRight==arrayRight.end())
    {
    //将左边剩下数据复制到原数组
    //array.erase(iterArray, iterEnd);
    //array.insert(iterArray, iterLeft, arrayLeft.end());
    while(iterLeft != arrayLeft.end())
    {
    *iterArray = *iterLeft;
    ++iterLeft;
    ++iterArray;
    }
    }
    return;
    }

    用此函数代替之前mergeSort()中的 subMerge即可。其中在将左边或右边剩余元素复制到原数组的时候,如果用 vector成员函数insert,

    必须先将iterArray所指位置右边的元素删除,不然会使iterArray右边的元素向后移动,导致元素个数增多。

  • 相关阅读:
    hdu 1695 GCD 欧拉函数 + 容斥
    E. Xenia and Tree 分块 + LCA
    二分图匹配 + 构造 E. Arpa’s overnight party and Mehrdad’s silent entering
    Win系统如何修改远程桌面端口3389
    centos7下使用selenium实现文件上传
    windows下tesseract-ocr的安装及使用
    windows下pycharm输入法跟随设置
    django 外键使用select html
    xstart访问centos7
    Centos7 安装VNC实现远程桌面
  • 原文地址:https://www.cnblogs.com/haigege/p/2299302.html
Copyright © 2011-2022 走看看