void merge(int *a1, int *a2, int *a3, int s1, int s2, int s3){
s2 -=1;
int track =0;
s3-=1;
int p2=0;
int p3=0;
while(p2<s2 && p3 <s3){
if(a2[p2]<a3[p3])
a1[track++]=a2[p2++];
else
a1[track++]=a3[p3++];
}
while(p2<s2) a1[track++]=a2[p2++];
while(p3<s3) a1[track++]=a3[p3++];
}
void msort(int *array, int n){
if(n<=1) return;
int a1_size = n/2;
int a2_size = n-n/2;
int a1[n/2];
int a2[n-n/2];
for(int i=0;i<n/2;i++){
a1[i] = array[i];
}
for(int i=0,j=n/2;j<n;i++,j++){
a2[i] = array[j];
}
msort(a1, n/2);
msort(a2, n-n/2);
merge(array, a1, a2, n, a1_size, a2_size);
}
int main(){
int a[]={1,2,1,2,3,94,5,67};
msort(a,8);
for(int i=0;i<8;i++)
cout << a[i] << endl;
}
Here is my code, and i expect it will return a sorted array.
I know the problem is about passing the address of array to merge will ammend data inside array and hence affect the result. I tried for a long time but still cant figure out how to ammend it. Would someone can give me a hint or help?
The problem is in
s2 -= 1ands3 -= 1statements. Why are you doing that? A standard idiom for iterating array from zero-basedindexis to count whileindex < length, not whileindex < length-1.A couple of other notes:
merge, that way at mostnints will be allocated at any time.std::vectorand/or iterator ranges instead of C-style arrays