Merge Sort code not working

I tried coding the merge sort algo after leaning the theory. Can’t understand what’s wrong in my code iOpr9P - Online C Compiler & Debugging Tool - Ideone.com

You should not use sizeof() operator for array parameters.

int sz = sizeof(a)/sizeof(a[0]);

This must not be used if you are passing ‘a’ as parameter array to some function.

‘sz’ will always be 1 in such case.

Have a look at this link - Do Not Use sizeof For Array Parameters in C - GeeksforGeeks
for explaination.

1 Like

you need to learn a lot .

http://geeksquiz.com/merge-sort/

This code is helpful for u. It is very simple code.

#include<bits/stdc++.h>
using namespace std;

#define mx 10

void merge(int arr[], int l, int m, int h)
{
int l1, l2, i;

l1 = l;
l2 = m + 1;
i = l;

int b[h+1];
// int *b = new int [h+l+1]; avabe dile dynamic memory allocation.
while(l1<=m && l2<=h)
{
  if(arr[l1]<=arr[l2])
  {
    b[i++] = arr[l1++];
  }

else
  {
   b[i++] = arr[l2++];
  }
}

while(l1<=m)
{
  b[i++] = arr[l1++];
}

while(l2<=h)
{
  b[i++] = arr[l2++];
}

for(i = l; i<=h; i++)
{
  arr[i] = b[i];
}
//delete b;
}

void sortion(int arr[], int low, int high)
{
int mid;

if(low < high)
{
  mid = (low + high) / 2;
  sortion(arr, low, mid);
  sortion(arr, mid+1, high);
  merge(arr, low, mid, high);
}

}

int main()
{
int i;
int arr[mx];

for(i=0; i<mx; i++) cin>>arr[i];

sortion(arr,0, mx-1);

for(i=0; i<mx; i++) cout<<arr[i]<<" ";

return 0;
}

the void mergeSort(int A[],int n) function only doesn’t have the left and right parameters, you should add this to your function like this: void mergeSort(int A[],int left,int right)

1 Like

made that change @ankitbisla21 . Still same error.Modified code