Search code examples
c++mergesort

I want to write merge sort in C++, but got some errors with memory and can't solve it


So there's my code and when I run it I'm getting run out of memory Could it depend on my computer or it's problem with code? Algorithm of merge sort I'd read at couple of sites, but nothing helped

#include <iostream>

using namespace std;

int quicksort (int m[], int left, int right)
 {
    int i = left;
    int j = right;
    int middle = m[(left + right) / 2];
    do{
        while (m[i] <= middle)
            i++;
        while (m[j] >= middle)
            j--;
        if (i <= j)
        {
            if (m[i] > m[j])
                swap (m[i], m[j]);
            i++;
            j--;
        }
    }while (i <= j);
    if (left < j)
        quicksort (m, left, j);
    if (i < right)
        quicksort (m, i, right);
}

int main ()
{
    int n, i;
    cin>> n;
    int m[n];
    for (i = 0; i <= n; i++)
        cin >> m[i];
    quicksort (m , 0, n - 1);
    for (i = 0; i <= n; i++)
        cout << m[i] << " ";
}

Solution

  • So it should work now, you went beyond the bounds of the array.

    #include <iostream>
    
    using namespace std;
    
    int quicksort (int m[], int left, int right)
     {
        int i = left;
        int j = right;
        int middle = m[(left + right) / 2];
        do{
            while (m[i] < middle)
                i++;
            while (m[j] > middle)
                j--;
            if (i <= j)
                if (m[i] > m[j])
                    swap (m[i], m[j]);
                i++;
                j--;
            }
        }while (i <= j);
    
        if (left < j)
            quicksort (m, left, j);
    
        if (i < right)
            quicksort (m, i, right);
    }
    
    int main () {
        int n, i;
        cin>> n;
        int m[n + 1];
        for (i = 0; i < n; i++){cin >> m[i];}
        quicksort (m , 0, n - 1);
        for (i = 0; i < n; i++){cout << m[i] << " ";}
    }