According to my algorithms book, this closed interval version of merge sort is properly implemented, which it is. However, I'd like to setup an open-ended interval version of this sort algorithm. What's the proper way to do this? Here's my current closed interval code:
#include <iostream>
using namespace std;
template<typename T>
void mergeHalf(T *src, uint start, uint mid, uint end)
{
T *temp = new T[end + 1];
uint lhs = start, rhs = mid + 1;
uint index = start;
while(lhs <= mid && rhs <= end)
{
if(src[lhs] <= src[rhs])
temp[index] = src[lhs++];
else
temp[index] = src[rhs++];
index++;
}
while(lhs <= mid)
temp[index++] = src[lhs++];
while(rhs <= end)
temp[index++] = src[rhs++];
for(index = start; index <= end; ++index)
src[index] = temp[index];
delete [] temp;
}
template<typename T>
void merge(T *src, uint start, uint end)
{
if(start < end)
{
// Add one to midpoint to even out size division
const uint m = start + (end - start) / 2;
merge(src, start, m);
merge(src, m + 1, end);
mergeHalf(src, start, m, end);
}
}
int main()
{
const size_t n = 6;
int myArray[n] = {5, 2, 3, 1, 7, 9};
merge(myArray, 0, n - 1);
for(size_t i = 0; i < n; ++i)
cout << myArray[i] << ' ';
cout << endl;
return 0;
}
I'm trying to alter this merge sort algorithm to work with an open ended range, i.e. calling merge(myArray, 0, n); instead of merge(myArray, 0, n - 1);
EDIT: As of now, something is wrong with the midpoint recursion when I'm passing in the size of the array and altering the loops to be open ended (non-inclusive). I've been trying to track the problem, but I can't see it at all.
Thanks for reading, any help is greatly appreciated; also, any language listed in the tags is okay. This algorithm is implemented in C++11 with GCC 4.9.2.