Doubt in merge sort code

this is the code

#include
using namespace std;
void sort(int a[],int si,int ei){
if(si>ei)
return;
int mi=(si+ei)/2;
sort(a,si,mi);
sort(a,mi+1,ei);
int i=si,j=mi+1;
int arr[1000];
int k=0;
for(;i<=mi && j<=si;){
if(a[i]<a[j]){
arr[k]=a[i];
k++;
i++;
}
else{
arr[k++]=a[j++];
}
}
while(i<=mi){
arr[k++]=a[i++];
}
while(j<=ei){
arr[k++]=a[j++];
}
i=si;
k=0;
for( ;i<=ei;i++){
a[i]=arr[k++];
}
}
int main(){
int a[6];
for(int i=0;i<6;i++){
cin>>a[i];
}
sort(a,0,5);
for(int i=0;i<6;i++){
cout<<a[i];
}
}

https://ide.codingblocks.com/s/75354 this is the link of the code

Hello Tushar … In the base codition if(si>ei) return there should be if(si>=ei) return because si will never be greater tha ei as u can see mi=(si+ei)/2 mi will always less than si as si and ei both are positive.

getting output which is same as input after doing the changes. it is not sorting them

for(;i<=mi && j<=si;) in place of si ei will be there since si is starting you must itirate till end ei.

  • for(;i<=mi && j<=ei;)

done
thanks a lot sir

1 Like