Merge Sort Algorithm

plz tell where my code is incorrect

#include
using namespace std;

void merge(long long int a[],long long int s,long long int e){
long long int temp[2000006];
long long int mid=(s+e)/2;
long long int i=s;
long long int j=mid+1;
long long int k=s;

while(i<=mid && j<=e){
    if(a[i]<=a[j]){
        temp[k]=a[i];
        k++;
        i++;
    }
    else{
        temp[k]=a[j];
        j++;
        k++;
    }
}

while(i<=mid){
    temp[k]=a[i];
    k++;
    i++;
}

while(j<=e){
    temp[k]=a[j];
    k++;
    j++;
}


for(int i=s;i<=e;i++){
    a[i]=temp[i];
}

}

void mergeSort(long long int a[],long long int s,long long int e){
// base case
if(s>=e){
return;
}

// rec case
long long int mid=(s+e)/2;
mergeSort(a,s,mid);
mergeSort(a,mid+1,e);


// merging the two arrays
merge(a,s,e);

}

int main() {
long long int n;
cin>>n;

long long int a[n];
for(long long int i=0;i<n;i++){
    cin>>a[i];
}
long long int s=0,e=n-1;
mergeSort(a,s,e);


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

}

Hey @krikhi
Your code works completely fine. Can you tell me what error are you getting?

Initially there was a run error but now after refreshing the testcases are getting passed.Sorry for the inconvenience.

1 Like