I tried to run my merge sort algorithm using recursion program on Xcode11 for MacOSx but I'm getting the following error - Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)
I'm not able to find the solution for this. Please find below the code that I used.
#include <iostream>
#include <vector>
using namespace std;
void printArray(vector<int> arr){
for(int x: arr){
cout<<x<<" ";
}
cout<<endl;
}
vector<int> mergeSort(vector<int> arr){
vector<int> B,C;
unsigned long Na = arr.size();
unsigned long Nb, Nc;
Nb = Na/2 + (Na%2);
Nc = Na - Nb;
for (int i =0;i<Na;i++){
if (i<Nb)
B.push_back(arr[i]);
else
C.push_back(arr[i]);
}
B = mergeSort(B);
C = mergeSort(C);
int i=0,j=0;
for(int k=0;k<Na;k++){
if(B[i]<C[j]){
arr[k] = B[i];
i++;
}
else if(C[j]<=B[i]){
arr[k] = C[j];
j++;
}
}
return arr;
}
int main() {
vector<int> A{5,4,1,8,7,2,6,3};
cout<<"Unsorted Array: "<<endl;
printArray(A);
A = mergeSort(A);
cout<<"Sorted Array: "<<endl;
printArray(A);
return 0;
}
You have infinite recursion. Your mergeSort
function always calls itself (twice), leading to a stack overflow.
At the very least you should put something like
if (arr.size() <= 1) return arr;
at the beginning of your function. But you may well have other problems too.
It took me about two minutes to find this problem using a debugger. I ran your code until it crashed, examined the call stack, and immediately saw the infinite recursion. You should learn how to use a debugger. Programming is much easier when you have this skill.
Kudos for providing a mre though.