合并排序(非哨兵方法)

//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右边的元素向后移动,导致元素个数增多。

转载于:https://www.cnblogs.com/haigege/archive/2011/12/23/2299302.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值