Answer the question
In order to leave comments, you need to log in
Why is my implementation of merge sort not working?
Please tell me why it doesn't work
#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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question