I am trying to implement a merge-sort
algorithm with the use of arrays
instead of vectors
and I am getting some errors in one of my two functions. The code of the two functions is below.
void Merge(int ar[], int ar1[], int ar2[], int n1, int n2) {
int p1 = 0;
int p2 = 0;
int p3 = 0;
while (p1 < n1 && p2 < n2) {
if (ar1[p1] < ar2[p2])
{
ar[p3]=ar1[p1];
p3++;
p1++;
}
else
{
ar[p3]=ar2[p2];
p3++;
p2++;
}
}
while (p1 < n1)
{
ar[p3]=ar1[p1];
p3++;
p1++;
}
while (p2 < n2)
{
ar[p3]=ar2[p2];
p3++;
p2++;
}
}
I figured out how to solve the problem I was facing with the code below.
void Sortmerge(int array[],int n) {
if (n <= 1) return;
if (n % 2 == 0)
{
int arr1[n/2];
int arr2[n/2];
int k=0;
int l=0;
for (int i=0;i<n;i++)
{
if (i<(n/2))
{
arr1[k++]=array[i];
}
else
{
arr2[l++]=array[i];
}
}
Sortmerge(arr1,n/2);
Sortmerge(arr2,n/2);
for (int i=0;i<n;i++)
{
array[i]=0;
}
Merge(array, arr1, arr2,n/2,n/2);
}
if (n%2!=0)
{
int arr1[(n-1)/2];
int arr2[(n+1)/2];
int k=0;
int l=0;
for (int i=0;i<n;i++)
{
if (i<((n-1)/2))
{
arr1[k++]=array[i];
}
else
{
arr2[l++]=array[i];
}
}
Sortmerge(arr1,(n-1)/2);
Sortmerge(arr2,(n+1)/2);
for (int i=0;i<n;i++)
{
array[i]=0;
}
Merge(array, arr1, arr2,(n-1)/2,(n+1)/2 );
}
}
sizeof(ar1)/sizeof(int)
doesn't do what you want, sincesizeof(ar1)
is the same assizeof(int*)