2

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;
}
  • 2
    More than likely, running outside of bounds.. and indeed so in this case. The bounds of B[i] and C[j] are not correctly checked. There is no guarantee these are <= B.size() and C.size(), respectively. The mergesort algorithm itself (pseudo code) avoids out-of-bounds errors. – user2864740 May 19 '20 at 16:37
  • 2
    Here is a suitable [valid] pseudo-code example: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation - explicitly note the `..i < iMiddle && (j >= iEnd..` used when merging. The same applies even when first splitting to two different collections, it just changes to suit the implementation. – user2864740 May 19 '20 at 16:44
  • 1
    Thank you for the Wikipedia source! I'll definitely check that out. – Adithya Venkat May 20 '20 at 20:45

1 Answers1

2

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.

john
  • 85,011
  • 4
  • 57
  • 81