C++ recursive initialization of vectors using iterators produce inconsistent results - c++

I was trying to practice C++ iterators by defining the very common mergesort algorithm when I encountered inconsistent program behavior. My question is NOT how to implement mergesort (which I both know and also realize has many example answers), but rather when creating recursive vectors using iterators that I receive inconsistent final results.
I'm aware that I could solve the issue by copying the values into L and R arrays through a for loop, but I would like to understand why using iterators is not working. This is running on CLION with C++ 14. This post Best way to extract a subvector from a vector? did not answer my question, as I'm creating vector similar to methods prescribed.
void merge2(vector<int> &arr, int l, int m, int r)
{
vector<int> L{arr.begin()+l, arr.begin()+m+1};
vector<int> R{arr.begin()+m+1,arr.begin()+r+1};
int i = 0, j = 0, k = l;
int n1 = m - l + 1;
int n2 = r - m;
while (i < (n1) && j < (n2)){
if (L[i]<=R[i]){ //R[i] is replaced by R[j]
arr[k] = L[i++];
}
else {
arr[k] = R[j++];
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while(j < n2){
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void merge2Sort(vector<int> &arr, int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
// int m = (l+r-l)/2;
// int m = l+(r-l)/2;
int m = (l+r)/2;
// Sort first and second halves
merge2Sort(arr, l, m);
merge2Sort(arr, m+1, r);
merge2(arr, l, m, r);
}
}
int main(int argc, char **argv){
vector<int> arr = {12, 11, 13, 5, 6, 7};
merge2Sort(arr, 0, arr.size()-1);
for(auto i = arr.begin(); i != arr.end(); i++){
cout << *i << " ";
}
return 0;
}
Sometimes I receive the correct answer 5 6 7 11 12 13 and other times the incorrect answer 5 6 7 11 13 12. The answer should not vary by attempt.
Correct Answer to reflect answer and comments. Answer corrects indexing error and relies upon iterators. Also noting from comments that vectors when initialized from iterators should use () and not {}.
template <class It>
void merge(It left, It middle, It right)
{
// Beeing generic, you need to retrieve the type.
using value_type = typename std::iterator_traits<It>::value_type;
// You can copy only the first half
std::vector<value_type> left_side_copy(left, middle);
It L = left_side_copy.begin();
It R = middle;
while (L != left_side_copy.end() && R != right)
{
if ( *L <= *R )
{
*left = *L;
++L;
}
else {
*left = *R;
++R;
}
++left;
}
// Copy only the leftovers, if there are any
std::copy(L, left_side_copy.end(), left);
}
template <class It>
void merge_sort(It left, It right)
{
if (auto dist = std::distance(left, right); dist > 1)
{
It middle = left + dist / 2;
merge_sort(left, middle);
merge_sort(middle, right);
merge(left, middle, right);
}
}
int main(void)
{
std::vector<int> arr {
5, 12, 11, 13, 5, 4, 7, 13, 6
};
merge_sort(arr.begin(), arr.end());
for(auto const &i : arr) {
std::cout << ' ' << i;
}
std::cout << '\n';
}

You're using index i instead of j in vector R. Replace R[i] with R[j] see below
void merge2(vector<int> &arr, int l, int m, int r)
{
//..
while (i < (n1) && j < (n2)){
if (L[i]<=R[j]){ //R[i] is replaced by R[j]
arr[k] = L[i++];
}
else {
arr[k] = R[j++];
}
k++;
}
//...
}

The line int m = l+(r-l)/2; is incorrect. You probably meant int m = (l+r-l)/2; although I think it would be better to keep int m = (l+r)/2;.

Related

What is wrong with my merge sort implementation refer to CLRS?

I tried to implement merge sort using C++, however, something went wrong. I have no idea what is wrong.
The following code is what I wrote based on CLRS. I think it is quite easy to understand the meaning.
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& nums, int p, int q, int r);
void mergeSort(vector<int>& nums, int p, int r){
if (p < r) {
int q = (p + r) / 2;
mergeSort(nums, p, q);
mergeSort(nums, q + 1, r);
merge(nums, p, q, r);
}
}
void merge(vector<int>& nums, int p, int q, int r) {
int s1 = p, s2 = q + 1;
vector<int> l1, l2;
for (int i = s1; i <= q; i++) {
l1.push_back(nums[i]);
}
for (int i = s2; i <= r; i++) {
l2.push_back(nums[i]);
}
int left = 0, right = 0;
int idx = 0;
while (left < l1.size() && right < l2.size()) {
if (l1[left] < l2[right]) {
nums[idx] = l1[left++];
}
else {
nums[idx] = l2[right++];
}
idx++;
}
while (left < l1.size()) {
nums[idx++] = l1[left++];
}
while (right < l2.size()) {
nums[idx++] = l2[right++];
}
}
int main() {
vector<int> vect;
vect.push_back(1);
vect.push_back(3);
vect.push_back(12);
vect.push_back(23);
vect.push_back(4);
vect.push_back(11);
vect.push_back(44);
vect.push_back(322);
mergeSort(vect, 0, vect.size() - 1);
for (int i = 0; i < vect.size(); i++) {
cout << vect[i] << endl;
}
return 0;
}
I want to use the program to sort some integers, however, it only shows many duplicate numbers. What's going on? I don't think there is a problem of the merge function.
The code needs a one line fix:
int idx = p; // not idx = 0
Optimized top down using arrays from Wiki article (note bottom up is slightly faster):
void TopDownMerge(int A[], int bgn, int mid, int end, int B[])
{
int i, j, k;
i = bgn, j = mid, k = bgn;
while(1){
if(A[i] <= A[j]){ // if left smaller
B[k++] = A[i++]; // copy left element
if(i < mid) // if not end of left run
continue; // continue
do // else copy rest of right run
B[k++] = A[j++];
while(j < end);
break; // and break
} else { // else right smaller
B[k++] = A[j++]; // copy right element
if(j < end) // if not end of right run
continue; // continue
do // else copy rest of left run
B[k++] = A[i++];
while(i < mid);
break; // and break
}
}
}
void TopDownSplitMerge(int B[], int bgn, int end, int A[])
{
if (end - bgn <= 1) // if run size == 1
return; // consider it sorted
int mid = (end + bgn) / 2;
TopDownSplitMerge(A, bgn, mid, B);
TopDownSplitMerge(A, mid, end, B);
TopDownMerge(B, bgn, mid, end, A);
}
void TopDownMergeSort(int A[], int n) // n = size (not size-1)
{
if(n < 2)
return;
int *B = new int [n]; // 1 time allocate and copy
for(size_t i = 0; i < n; i++)
B[i] = A[i];
TopDownSplitMerge(B, 0, n, A); // sort data from B[] into A[]
delete B;
}
Afterwards, I finally get to fix the bugs of my program. After modification, here is the code:
class Solution {
public:
vector<int> temp;
vector<int> sortArray(vector<int>& nums) {
temp.resize((int)nums.size(), 0);
mergeSort(nums, 0, nums.size() - 1);
return nums;
}
void mergeSort(vector<int>& nums, int start, int end) {
if (start >= end) return;
int middle = (start + end) / 2;
mergeSort(nums, start, middle);
mergeSort(nums, middle + 1, end);
merge(nums, start, middle, end);
}
void merge(vector<int>& nums, int leftStart, int middle, int rightEnd) {
int leftEnd = middle;
int rightStart = middle + 1;
int i = leftStart, j = rightStart;
int index = 0;
while (i <= leftEnd && j <= rightEnd) {
if (nums[i] < nums[j]) {
temp[index] = nums[i++];
}
else {
temp[index] = nums[j++];
}
index++;
}
while (i <= leftEnd) {
temp[index++] = nums[i++];
}
while (j <= rightEnd) {
temp[index++] = nums[j++];
}
for (int i = 0; i < rightEnd - leftStart + 1; i++) {
nums[i + leftStart] = temp[i];
}
}
};
Here is something should be careful next time:
In the merge part, it is difficult to merge in place. It'd be better to use another temp array to store the merged results and update to the target array (nums in this case).
Readable identifers is very recommended (Although the pseudocode of CLRS may not use that part).
Need to use debuggers to find the bug of program {However, it takes like forever to load local variables of VS Code debugers.

MergeSort: Is my problem from incorrect indeces or instance variables with recursion

I'm currently reading CLRS while also trying to learn C++. As you can imagine everything is going great! I've been stuck on understanding MergeSort but over the last couple days have made good progress and feel like my code is almost there.
P.S. Java is my strong suit so if I mix up the vocab between languages I apologize!
I imagine the problem is stemming from one of the few issues below:
1)Because I'm still new to C++ I've read that during instances it's important to use the class variables in the way I have below in order to apply the size of the array throughout your code. With that being said, I think during my recursion the fact that my r variable is a read-only constant; it is making my code go through an extra iteration of the recursion which is leading to problems.-My solution to this was to just set that variable equal to a new one and have it adapt to the array as needed. This still lead to wrong solutions! 2)I've read numerous times to not use Arrays in C++ especially in situations such as this and to use vectors instead. Given that I haven't learned about vectors quite yet, I felt more comfortable using Arrays and believe an issue may be from incorrect coding of pointers and references in my program.3)My final assumption also comes from reading a lot of answers to similar questions which is to not use instance variables in recursive methods. I'm pretty sure this wasn't a problem in Java and felt like this may just be a big no-no in C++ specifically.
I've seen countless classes of MergeSort and am very confident that my mergeSort & merge methods are perfect which makes me believe that this problem is probably just a lack of knowledge to C++ syntax or rules! Any comments or help would be greatly appreciated! Lastly 2 results of arrays I got quite often were [2, 4, 4, 5, 4, 4, 5, 1] & [2, 4, 5, 4, 5, 7, 1]
#include <iostream>
#include <cmath>
using namespace std;
class MergeSort
{
static const size_t r = 8;
int A[r];
public:
MergeSort() : A{2, 4, 5, 7, 1, 2, 3, 6}
{
printMergeSort(A, r);
int p = 0;
mergeSort(A, p, r);
printMergeSort(A, r);
}
static void mergeSort(int *A, int p, int r)
{
if(p < r)
{
//int q = floor(((p + r) / 2));
int q = ((p + r) / 2);
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
merge(A, p, q, r);
}
}
static void merge(int *A, int q, int p, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int L[n1+1];
int R[n2+1];
for(int i = 0; i < n1; i++)
{
L[i] = A[p + i];
}
for(int j = 0; j < n2; j++)
{
R[j] = A[q + j + 1];
}
//L[n1 + 1] = std::numeric_limits<int>::max();
L[n1] = INT_MAX;
R[n2] = INT_MAX;
int i = 0;
int j = 0;
for(int k = p; k <= r; k++)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i = i + 1;
}
else
{
A[k] = R[j];
j = j + 1;
}
}
}
static void printMergeSort(int *A, size_t r)
{
for(int i = 0; i < r; i++)
{
cout << A[i] << " ";
}
cout << endl;
}
};
int main()
{
//MergeSort();
MergeSort x;
return 0;
}
You are on right track, the best approach to learning practice algorithms are implementing them in a programming language.
Regarding your question, i think the issue is in your merging function.
In merging function what you want to do is to move through both smaller arrays and pick the smallest value and store it in the temporary register.
For example if you have
{2, 7}
{4, 6}
you want to pick "2" first and increment the pointer pointing to beginning of first array and then pick "4" and "6", and finally "7".
I posted the corrected version of your code here with minor variable naming changes.
Here are also some notes:
constructor is not a good place to call your functions. I modified your code in a way that the merge sort and printing is called in main function.
To find mid, you do not need to use floor. When you divide two integer numbers the result will be an integer as well. i.e: (3+4)/2 = 3
#include
#include
using namespace std;
const int INT_MAX = 2147483647;
class MergeSort
{
static const size_t r = 8;
int A[r];
public:
MergeSort() : A{2, 4, 5, 7, 1, 2, 3, 6}
{
//printMergeSort(A, r);
int p = 0;
//mergeSort(A, p, r);
//printMergeSort(A, r);
}
void mergeSort () {
mergeSortUtil (A, 0, r-1);
}
static void mergeSortUtil(int *A, int p, int r)
{
if(p < r)
{
int mid = (p + (r-p) / 2);
mergeSortUtil(A, p, mid);
mergeSortUtil(A, mid + 1, r);
merge(A, p, mid, r);
}
}
static void merge(int *A, int low, int mid, int high)
{
int left=low;
int right = mid+1;
int i=low;
int res[high-low+1];
while (left<=mid && right <=high) {
if(A[left] < A[right]) {
res[i] = A[left];
left++;
} else {
res[i]=A[right];
right++;
}
++i;
}
while (left<=mid) {
res[i] = A[left];
left++;
i++;
}
while (right <=high) {
res[i]=A[right];
right++;
i++;
}
for (int i=low; i<=high; ++i) {
A[i]=res[i];
}
}
void printMergeSort()
{
for(int i = 0; i < r; i++)
{
cout << A[i] << " ";
}
cout << endl;
}
};
int main() {
//MergeSort();
MergeSort * x = new MergeSort();
x->printMergeSort();
x->mergeSort();
x->printMergeSort();
return 0;
}
One immediate problem is calling merge(A, p, q, r), while merge takes its arguments as (int *A, int q, int p, int r). See how p and q are mixed up?
Another problem, less obvious, is the semantics of r. An initial invocation passes 8, which implies that r is one-past the end-of-range, and does not belong to the range. However,
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
imply that q in the first invocation does belong. You should make up your mind. Usually passing one-past leads to simpler and cleaner code. Consider
mergeSort(A, p, q);
mergeSort(A, q, r);
and
int n1 = q - p;
int n2 = r - q;
int L[n1];
int R[n2];
(no need to strange INT_MAX assignments anymore).
Of course, the main merge loop is wrong. This was addressed in the answer above. However, to emphasize the one-past argument, consider
while ((i < n1) && (j < n2)) {
if(L[i] <= R[j])
{
A[k++] = L[i++];
} else {
A[k++] = R[j++];
}
}
while (i < n1) {
A[k++] = L[i++];
}
while (j < n2) {
A[k++] = R[j++];
}

Quick Sort program stopped working

I was trying to solve the quick sort - 2 challenge on hackerrank. It said that we had to repeatedly call partition till the entire array was sorted. My program works for some test cases but for some it crashes, "Quick Sort - 2.exe has stopped working". I couldn't find the reason as to why it's happening.
The first element of the array/sub-array was to be taken as pivot element each time.
#include <iostream>
#include <conio.h>
using namespace std;
void swap(int arr[], int a, int b)
{
int c = arr[a];
arr[a] = arr[b];
arr[b] = c;
}
void qsort(int arr[], int m, int n) //m - lower limit, n - upper limit
{
if (n - m == 1)
{
return;
}
int p = arr[m], i, j, t; //p - pivot element, t - temporary
//partition
for (int i = m+1; i < n; i++)
{
j = i;
if (arr[j] < p)
{
t = arr[j];
while (arr[j] != p)
{
arr[j] = arr[j-1];
j--;
}
arr[j] = t; //pivot is at j and j+1
}
}
//check if sorted
int f = 1;
while (arr[f] > arr[f-1])
{
if (f == n-1)
{
f = -1;
break;
}
f++;
}
if (f == -1)
{
cout << "Sub Array Sorted\n";
}
else
{
if (p == arr[m]) //pivot is the smallest in sub array
{
qsort(arr, m+1, n); //sort right sub array
}
else
{
qsort(arr, m, j+1); //sort left sub array
qsort(arr, j+1, n); //sort right sub array
}
}
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
qsort(arr, 0, n);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
You have an index out of range problem.
This will not give you the solution, but it may help you to find the reason why your program fails.
I have modified your program so it uses a vector of int rather than a raw array of int, and when you run this program you get an index out of range exception.
The sequence 4 3 7 1 6 4 that triggers the problem is hardcoded, so you don't need to type it each time.
#include <iostream>
#include <vector>
using namespace std;
void swap(vector<int> & arr, int a, int b)
{
int c = arr[a];
arr[a] = arr[b];
arr[b] = c;
}
void qsort(vector<int> & arr, int m, int n) //m - lower limit, n - upper limit
{
if (n - m == 1)
{
return;
}
int p = arr[m], j, t; //p - pivot element, t - temporary
//partition
for (int i = m + 1; i < n; i++)
{
j = i;
if (arr[j] < p)
{
t = arr[j];
while (arr[j] != p)
{
arr[j] = arr[j - 1];
j--;
}
arr[j] = t; //pivot is at j and j+1
}
}
//check if sorted
int f = 1;
while (arr[f] > arr[f - 1])
{
if (f == n - 1)
{
f = -1;
break;
}
f++;
}
if (f == -1)
{
cout << "Sub Array Sorted\n";
}
else
{
if (p == arr[m]) //pivot is the smallest in sub array
{
qsort(arr, m + 1, n); //sort right sub array
}
else
{
qsort(arr, m, j + 1); //sort left sub array
qsort(arr, j + 1, n); //sort right sub array
}
}
}
int main()
{
vector<int> arr = { 4,3,7,1,6,4 };
qsort(arr, 0, arr.size());
for (unsigned int i = 0; i < arr.size(); i++)
{
cout << arr[i] << " ";
}
return 0;
}
First of all, what you made is not quick sort, but some combination of divide-ans-conquer partitioning and insert sort.
Canonical quicksort goes from from lower (p) and upper (q) bounds of array, skipping elements arr[p]m respectively. Then it swaps arr[p] with arr[q], increments/decrements and checks if p>=q. Rinse and repeat until p>=q. Then make calls on sub-partitions. This way p or q holds pivot position and subcalls are obvious.
But you are doing it different way: you insert elements from right side of subarray to left side. Such thing can produce O(N^2) time complexity for one iteration. Consider 1,0,1,0,1,0,1,0,1,0,1,0,... sequence, for example. This can increase worst case complexity over O(N^2).
Out of time complexity... The problem in your function lies in assumption that j holds pivot location in subcalls:
qsort(arr, m, j+1); //sort left sub array
qsort(arr, j+1, n); //sort right sub array
Actually, j is set again and again equal to i in your main for loop. If last element is equal or greater than pivot, you end up with j=n-1, the you call qsort(arr, n, n) and first lines check is passed (sic!), because n-n != 1.
To fix this you should do two things:
1) find pivot location directly after rearrange:
for (int i = m; i < n; i++)
if (p == arr[i])
{
j = i;
break;
}
or initialize it in different variable, update after this line:
arr[j] = t; //pivot is at j and j+1
and update recursive calls to use new variable instead of j
2) make a more bulletproof check in the beginning of your function:
if (n - m <= 1)
the latter will be enough to get some result, but it will be much less effective than your current idea, falling down to probably O(N^3) in worst case.

Error with Mergesort implementation in C++

I am learning to implement a mergesort algorithm for use to count inversions. Here is my current implementation of mergesort. However it is not working as it does not return a sorted array. Will anyone be able to tell me what is being done wrongly in this code which I have written? It should sort the array v which is input into the function.
void mergeCountInversion(vector<int> v, int l, int r)
{
if (l >= r)
{
return;
}
int m = (l + r)/2;
//call merge sort to return two sorted arrays
mergeCountInversion(v, l, m);
mergeCountInversion(v, m+1, r);
int left = l;
int right = m+1;
std::vector<int> vtemp ;
//merge and sort the two sorted array, storing the sorted array in vtemp
for (int k = l; k <= r; ++k){
if (left >= m+1)
{
vtemp.push_back(v[right]);
right++;
}
else if (right > r)
{
vtemp.push_back(v[left]);
left++;
}
else
{
if (v[left] <= v[right])
{
vtemp.push_back(v[left]);
left++;
}
else{
vtemp.push_back(v[right]);
right++;
count += m + 1 - left;
}
}
}
//replace v with the sorted array vtemp
for (int i = 0; i < vtemp.size(); ++i)
{
v[l+i] = vtemp[i];
}
}
There are several issues in your code.
You are passing the vector by value, but you should pass it by refernce.
If you declare the function as void You can't return 0;, just return;.
When you create vtemp you should know exactly its size: r - l. So you can reserve memory for it and you don't need to push_back.
You have to pass count to the function too.
Your function can be:
void mergeCountInversion(vector<int> & v, int l, int r, int & count) {
if (l >= r) return;
int m = (l + r)/2;
//call merge sort to return two sorted arrays
mergeCountInversion(v, l, m, count);
mergeCountInversion(v, m+1, r, count);
int left = l;
int right = m+1;
std::vector<int> vtemp(r-l);
//merge and sort the two sorted array, storing the sorted array in vtemp
for (int k = l; k <= r; ++k) {
if (left >= m+1) {
vtemp[k] = v[right];
right++;
}
else if (right > r) {
vtemp[k] = v[left];
left++;
}
else {
if (v[left] <= v[right]) {
vtemp[k] = v[left];
left++;
}
else {
vtemp[k] = v[right];
right++;
count += m + 1 - left;
}
}
}
//replace v with the sorted array vtemp
for (int i = 0; i < vtemp.size(); ++i)
v[l+i] = vtemp[i];
}
You defined
void mergeCountInversion(vector<int> v, int l, int r)
then you first call mergeCountInversion recursively, and modify v after the calls returned.
The problem is that the changes to v made in the recursive calls will never be seen, because v is passed by value.
Try to pass v by reference:
void mergeCountInversion(vector<int>& v, int l, int r)
such that all calls work on the same copy of v.

Issue with Merge Sort implementation in C++

I am getting two errors in implementing the algorithm from pseudocode:
One of my problems is int L[n1+1]; error: needs to be a constant; cannot allocate constant size 0. The only way to run this is to make the size a number like 10. I may be implementing the psuedocode wrong that is why I included the statement above that. This may be the cause of my next problem.
My other problem is I am printing only one line of code unsorted. My print function is flawless and works for all of the sorting programs. I believe the MERGE function is only running once. I posted the output of the Sort at the bottom.
I have a random number generator for the array A, from 0 to RAND_MAX.
Initial call is MERGESORT(A,1,n);
void MERGE(int *A, int p, int q, int r)
{
int n1 = q-(p+1);
int n2 = r-q;
//psuedocode states, let L[1..n1+1] & R[1..n1+1] be new arrays
int L[n1+1];
int R[n2+1];
for(int i=1; i<n1;i++)
{
L[i]=A[p+(i-1)];
}
for(int j=1; j<n2; j++)
{
R[j] = A[q+j];
}
L[n1+1]=NULL; //sentinel
R[n2+1]=NULL; //sentinel
int i=1;
int j=1;
for (int k=p; k<r; k++)
{
if(L[i]<=R[j])
{
A[k]=L[i];
i=i+1;
}
else
{
A[k]=R[j];
j=j+1;
}
}
}
void MERGESORT(int *A,int p, int r)
{
if (p<r)
{
int q=floor((p+r)/2);
MERGESORT(A,p,q);
MERGESORT(A,q+1,r);
MERGE(A,p,q,r);
}
}
With int L[10]; and my A[10]; my output is:
Sort: 7474 28268 32506 13774 14411
Press any key to continue . . .
If someone could just assist in the two problems, I more than likely will get it to work.
You are failing to detect the end of your merge arrays:
for (int k=p; k<r; k++)
{
// You need to check that i/j are still in range.
// otherwise the following test are not valid.
if ((i < n1) && (j < n2))
{
if(L[i]<=R[j])
{
A[k]=L[i];
i=i+1;
}
else
{
A[k]=R[j];
j=j+1;
}
}
else
{ /* More work here */
}
Other comments:
Identifiers that are all capitol MERGE MERGESORT are generally reserved for macros. If you use them you are likely to hit problems. Prefer function names of mixed case.
You can simulate arrays with vector:
// Simulate L[1..n1+1]
minI = 1;
maxI = n1-1;
std::vector<int> const L(A+(minI-1), A+(maxI-1));
Arrays in C++ are zero indexed. You seem to be having off by one errors (especially in accessing the end of the array). I would advice you to start the count at 0 rather than 1. Most C++ code is written in terms of iterators from [begining..1PastEnd). I think you will find your algorithm easier to implement if you adapt that style.
There are several issues with your code, I've pointed them out in comments. This is a solution closest to your code, and it's far from best. Consider using C++ containers, like std::vector for example. Naming is at least disputable, and of course merge sort should be implemented as an in place algorithm.
//L and R are auxiliary arrays
//preallocated with (inputSize/2 + 1) constant size
void MERGE(int *A, int p, int q, int r, int* L, int* R)
{
if (p > q || q > r)
{
return;
}
int n1 = q - p + 1;
int n2 = r - q;
// note 0-based indices
int i = 0;
int j = 0;
for(;i < n1;i++)
{
L[i] = A[p + i];
}
for(;j < n2;j++)
{
R[j] = A[q + j + 1]; //+1 because p + n1 - 1 == q + 0
}
//again - note 0-based indices
i = 0;
j = 0;
for (int k = p; k <= r; ++k)
{
// The most important fix - in your code you didn't check
// for left/right array bounds at all.
// Sentinel values aren't needed - size is known
if(i < n1 && (j >= n2 || L[i] <= R[j]))
{
A[k] = L[i];
++i;
}
else if (j < n2)
{
A[k] = R[j];
++j;
}
}
}
void MERGESORT(int* A, int p, int r, int* L, int* R)
{
if (p < r)
{
int q = (p + r) / 2; //floor was redundant
MERGESORT(A, p, q, L, R);
MERGESORT(A, q+1, r, L, R);
MERGE(A, p, q, r, L, R);
}
}
void MERGESORT(int* A, int size)
{
int*L = new int[size/2 + 1]; //preallocate auxiliary arrays
int*R = new int[size/2 + 1]; //size/2 + 1 is what will be needed at most
MERGESORT(A, 0, size - 1, L, R);
delete L;
delete R;
}
int main()
{
int A[5]{ 7474, 28268, 32506, 13774, 14411 };
MERGESORT(A, 5);
for (int i = 0;i < 5;++i)
{
std::cout << A[i] << std::endl;
}
return 0;
}
Output:
7474
13774
14411
28268
32506
Credit goes also to DyP for spotting all the mistakes in the previous version :)