Reputation: 415
I am trying to do merge algorithm based on stl vector and iterator, i know there is also std::merge, but I would like to make my own version, I want to average two iterator and gain the middle index as I did in normal integeriMiddle = (iEnd + iBegin) / 2
. Nevertheless, it never work, then I try to add value after by getting the vector size and divided by 2
iMiddle = iBegin+A.size()/2;
, but this is kind of stubid method to do and also run into problem when split more than 1 time, does any one have better solution for this?
void TopDownMergeSort(int n, vector<int> A, vector<int> B)
{
TopDownSplitMerge(A, A.begin(), A.end(), B);
}
void TopDownSplitMerge(vector<int> A, vector<int>::iterator iBegin, vector<int>::iterator iEnd, vector<int> B)
{
vector<int>::iterator iMiddle;
// if run size == 1
if((iEnd - iBegin) < 2){
cout<<"merge finshed!"<<endl;
return; // consider it sorted
}
iMiddle = iBegin+A.size()/2;
TopDownSplitMerge(A, iBegin, iMiddle, B); // split / merge left half
}
UPDATE
USE
iMiddle = iBegin+distance(iBegin,iEnd)/2;
Everything works fine!
Upvotes: 1
Views: 434