Algorithm: Can you Help me with my MergeSort implementation?
Hello there!
Glad to be a new member here!
I'm new to c++ coding, and I'm taking an algorithms course, and I've been having the hardest time implementing one of the basic Algorithms Merge-Sort, For those who recall how it works; My Merge-Step works fine
Code:
void merge(vector<int> array, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
vector<int> left, right;
vector<int>::iterator a_it = array.begin();
for(int i = 0; i != n1; ++i)
left.push_back(*(a_it + p + i -1));
left.push_back(1000000); //sentinel
for(int j = 0; j != n2; ++j)
right.push_back(*(a_it + q + j));
right.push_back(1000000); //sentinel
array.clear();
vector<int>::iterator i = left.begin(), j = right.begin();
for(int k = 0; k < r; ++k) {
if(*i <= *j) {
array.push_back(*i);
++i;
} else {
array.push_back(*j);
++j;
}
}
}
However my MergeSort recursive implementation does not work :(
Code:
void mergesort(vector<int> array, int p, int r) {
if(p < r) {
int q = floor((p + r) / 2);
mergesort(array, p, q);
mergesort(array, q + 1, r);
merge(array, p, q, r - 1);
}
}
The above code is based on the CLRS text book, So.. If I print the Array from within mergesort, it doesn't output the sorted array :(
Can you help me? Can you possibly spot where are the errors? I'm truly clueless..
Thanks in advance,
Best Regards,
J