Thread: sorted two array and result array

1. sorted two array and result array

Hi
I write function that take 5 parameters: pointer to array a, pointer to array b, size of array a, size of array b and pointer to size of result array
My task is to sort first array remove duplicates, this same with second array and include this two array. My code below

Code:
```#include <stddef.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return *(int*)a-*(int*)b;
}

int *testit(const int *a, const int *b, size_t az, size_t bz, size_t *cz) {
int *res;
size_t i,j;
qsort(a,az,sizeof(int),compare);
qsort(b,bz,sizeof(int),compare);

res=(int*)malloc(sizeof(int)*(az+bz));
for(i=0,j=0;i<az;)
{
if(a[i]!=a[i+1])
res[j++]=a[i++];
if(a[i]==a[i+1])
{
while((a[i]==a[i+1])&&(i<az))
i++;
res[j++]=a[i++];
}
}
for(i=0;i<bz;)
{
if(b[i]!=b[i+1])
res[j++]=b[i++];
if(b[i]==b[i+1])
{
while((b[i]==b[i+1])&&(i<bz))
i++;
res[j++]=b[i++];
}
}
*cz=j;
qsort(res,*cz,sizeof(int),compare);
return res;
}```
I got some errors from server
Code:
```ERROR < incorrect array length >
Array a:   {1}
Array b:   {2, 3, 4}
Expected:  {1, 2, 3, 4}
Submitted: {1, 1, 2, 3, 4}
```
Can you tell me where is mistake

2. I have changed the code but I still got message
Test Crashed
Caught unexpected signal: SIGSEGV (11). Invalid memory access.
Code:
```#include <stddef.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return *(int*)a-*(int*)b;
}

int *testit(const int *a, const int *b, size_t az, size_t bz, size_t *cz) {
int *res;
size_t i,j;
qsort(a,az,sizeof(int),compare);
qsort(b,bz,sizeof(int),compare);

res=(int*)malloc(sizeof(int)*(az+bz));
for(i=0;
for(i=0;i<bz;)
{
if(b[i]!=b[i+1])
res[j++]=b[i++];
if(b[i]==b[i+1])
{
while((b[i]==b[i+1])&&(i<bz))
i++;
res[j++]=b[i++];
}
}
*cz=j;
qsort(res,*cz,sizeof(int),compare);
return res;
}```

3. I suggest that you rename testit to distinct_merge or unique_merge or something like that. Before you implement unique_merge, implement two other functions, making sure you test them to be sure they work individually: remove_duplicates and merge.

remove_duplicates takes a pointer to a sorted array and the size of the array, then removes the duplicates in-place, returning the final number of elements in use. This in-place removal can be done by overwriting the duplicates by copying the unique values in their place, then you just don't care about the remaining elements beyond the number you return.

merge would take the same parameters as unique_merge, except that it assumes that the arrays are already sorted with the duplicates removed.

You then implement unique_merge using qsort, remove_duplicates, and merge.