H
H
Homemade2021-01-06 21:15:42
C++ / C#
Homemade, 2021-01-06 21:15:42

Why is my implementation of merge sort not working?

Please tell me why it doesn't work

This
#include <bits/stdc++.h>

using namespace std;

void Merge(int *a,int l,int q,int r)
{
    int sz = r-l+1, s = l;
    bool side = false;
    vector<int> b(sz);
    int mr = q + 1,ml = q,i = 0;
    while((l<=ml)&&(mr<=r)){
        if(a[l]<a[mr]){
            b[i] = a[l];
            l++;
        }else{
            b[i] = a[mr];
            mr++;
        }
        if(l>ml){
            side = true;
        }
        i++;
    }
    if(side){
        for(int j=mr;j<=r;j++){
            b[i] = a[j];
            i++;
        }
    }else{
        for(int j=l;j<=ml;j++){
            b[i] = a[j];
            i++;
        }
    }
    for(int t=s;t<=r;t++)
        a[t] = b[t];
}

void Merge_Sort(int *a,int l,int r)
{
    if(r>l){
        int q = (r+l)/2;
        Merge_Sort(a,l,q);
        Merge_Sort(a,q+1,r);
        Merge(a,l,q,r);
    }
}

int main()
{
    int n;
    cin>>n;
    int *a = new int[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    Merge_Sort(a,0,n-1);


    cout<<endl;

    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";

    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-01-07
@Homemade

When copying back from temporary array b to array a, you have an indexing error. Even though b is indexed from 0, you are accessing elements starting from s.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question