Here's my code for the merge sort algorithm:
In the meregesort function, I want to store the size of the array 'arr' in the variable 'n'. As strlen() doesn't work with integer arrays, I am using this expression to calculate the size: n=sizeof(arr)/sizeof(arr[0]).
But this expression is storing '1' in n (maybe treating arr just as an int type pointer, therefore 4/4=1) and hence since 1<2 , the function is just simply returning.
How to calculate the size of the passed array?
Code:
#include <iostream>
using namespace std;
void merge_(int *, int *, int *);
void mergesort(int *);
int main(){
int arr[]={7, 2, 1, 3, 6, 8, 10, 9, 5, 4};
mergesort(arr);
cout<<"Array after merge sorting:\n\n";
for(int i=0; i<10; i++){
cout<<arr[i]<<"\t";
}
return 0;
}
void merge_(int *l, int *r, int *arr){
int i=0, j=0, k=0;
int nL, nR;
nL=sizeof(l)/sizeof(l[0]);
nL=sizeof(r)/sizeof(r[0]);
while(i<nL && j<nR){
if(l[i]<=r[j]){
arr[k]=l[i];
k++;
i++;
}
else{
arr[k]=r[j];
k++;
j++;
}
}
while(i<nL){
arr[k]=l[i];
i++;
k++;
}
while(j<nL){
arr[k]=r[i];
j++;
k++;
}
}
void mergesort(int *arr){
int n;
n=sizeof(arr)/sizeof(arr[0]);
//cout<<n<<"\n";
if(n<2){
return;
}
int mid;
mid=n/2;
int left[mid];
int right[n-mid];
int i;
for(i=0; i<(mid-1); i++){
left[i]=arr[i];
}
for(i=mid; i<n; i++){
right[i-mid]=arr[i];
}
mergesort(left);
mergesort(right);
merge_(left, right, arr);
}
But this expression is storing '1' in n (maybe treating arr just as an int type pointer, therefore 4/4=1) and hence since 1<2 , the function is just simply returning.
How to calculate the size of the passed array?
Comment