# my mergesort program does not perform sort what is the error i could not get it?

void merge(int L[],int R[],int A[]){
int nL=sizeof(L)/sizeof(L[0]);
int nR=sizeof®/sizeof(R[0]);
int i=0,j=0,k=0;
while(i<nL && j<nR){
if(L[i]<=R[j]){
A[k]=L[i];
i++;}
else{
A[k]=R[j];
j++;
}
k++;
}
while(i<nL){
A[k]=L[i];
i++;
k++;
}
while(j<nR){
A[k]=R[j];
j++;
k++;
}
}
void mergeSort(int A[]){
int n=sizeof(A)/sizeof(A[0]);
if(n<2)
return;
int mid=n/2;
int left[mid];
int right[n-mid];
for(int i=0;i<mid;i++)
{
left[i]=A[i];
}
for(int i=mid;i<n;i++){
right[i-mid]=A[i];
}

``````        mergeSort(left);
mergeSort(right);
merge(left,right,A);

}
``````

void printArray(int *A,int size){
for(int i=0;i<size;i++){
cout<<A[i]<<endl;
}}

You can learn why your program isn’t producing correct output HERE.In main function let’s say you declared an array then in main function sizeof operator will produce correct output for size of array. But when yoou pass an array to any other function then you do not pass the whole array you just pass the pointer to first element of array by value. So the sizeof operator inside that function produces the sizeof that pointer. That’s why your functions are not working correct to avoid this you should explicitly pass the size of array along with the pointer to first element of array.

I hope, It helps

I did the exact same thing in JAVA. Hope it will help you.

public class MergeSort {

``````public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {2,4,1,6,8,5,3,7};
mergeSort(arr);
for (int i : arr) {
System.out.print(i+" ");
}
}

private static void mergeSort(int[] arr) {
// TODO Auto-generated method stub
int len = arr.length;
if (len < 2) {     //< for lesser than symbol
return;
}
int mid = len / 2;
int len_left = mid;
int len_right = len - mid;
int [] left = new int[len_left];
int [] right = new int[len_right];
for (int i = 0; i < left.length; i++) {
left[i] = arr[i];
}
for (int i = mid; i < len; i++) {
right[i - mid] = arr[i];
}
mergeSort(left);
mergeSort(right);
merge(left,right,arr);
}

private static void merge(int[] left, int[] right, int[] arr) {
// TODO Auto-generated method stub
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++; k++;
}
else{
arr[k] = right[j];
j++; k++;
}
}
while (i < left.length) {
arr[k] = left[i];
i++; k++;
}
while (j < right.length) {
arr[k] = right[j];
j++; k++;
}
}
``````

}