Why MergeSort is showing TLE for bigger numbers? How can i rectify it?

#include
using namespace std;

void merge(int *a, int s, int e){
// 5 things
int mid = (s+e)/2;
int i = s;
int j = mid+1;
int k = s;
int temp[500001] = {0};

//merge
// elements present in both arrays
while(i<=mid and j<=e){
	if(a[i]>a[j]){
		temp[k++] = a[j++];
	}
	else{
		temp[k++] = a[i++];
	}
}

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

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

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

}

void mergesort(int *a,int s, int e){
//base case only on element left
if(s>=e){
return;
}

int mid = (s+e)/2;

// call merge sort on both the arrays ; smaller one or bigger one
mergesort(a,s,mid);
mergesort(a,mid+1,e);

// call merge to merge this up
merge(a,s,e);

return;

}

int main() {
int n;
cin>>n;
int a[500001]={0};
for(int i=0;i<n;i++){
cin>>a[i];
}
mergesort(a,0,n-1);

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

}

@PNG_Mayank
make the temp[] array global and don’t initialise it inside merge() function

oh yes, thank you! But why was it working for the base case?

Actually Your code will work for small case which have less number of merge function recursive call. As n increase, you code would not work because number of merge() recursive call increase with increase in n and for each recursive call your code create new temp[] array. If n is high your program don’t have enough space to create temp[] array and eventually result in error.

@PNG_Mayank
As I can see you have successfully submitted the code. Please mark it as esolved.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.