the cursor not even going inside the msort function when I debugged it help me with what's wrong with my code
#include<stdio.h>
#include<conio.h>
void merge(int arr[],int low,int mid,int high){
int i=0,j=mid 1,brr[high-low 1],k=0;
while(i<=mid&&j<=high){
if(arr[i]<=arr[j]) brr[k ]=arr[i ];
else brr[k ]=arr[j ];
}
if(j<high) while(j<=high) brr[k ]=arr[j ];
else while(i<=mid) brr[k ]=arr[i ];
for(k=low;k<=high;k ){
arr[k]=brr[k];
}
}
void msort(int arr[],int low,int high){
int mid=(low high)/2;
if(low<high){
msort(arr,low,mid);
msort(arr,mid 1,high);
merge(arr,low,mid,high);
}
}
void main(){
int arr[]={23,54,-1,76,1,90,34,56};
int len=8;
printf("before sorting");
for(int i=0;i<len;i ) printf("%d,",arr[i]);
printf("\nafter sorting");
msort(arr,0,len-1);
for(int i=0;i<len;i ) printf("%d",arr[i]);
}
the cursor is stopping at the msort() function and the program is terminating
CodePudding user response:
You most likely suffer from a crash due to undefined behaviour because of exceeding array bounds:
for (k = low; k <= high; k )
{
arr[k] = brr[k];
// ^ (!)
}
k
goes up from low
to high
including, brr
's valid indices are from 0 to high - low
, though, and you exceed the array by low
elements (and skipping that many ones at the beginning).
for (k = low; k <= high; k )
{
arr[k] = brr[k - low];
// ^^^^^
}
solves the issue.