Reputation:
I am trying to code up a "generic" mergeSort in C:
void mergeSort(void *arr, int begin, int end,int size,
int (*comp)(void *, void *));
But since you need a holder/temp array, it becomes a bit tricky. I am not sure how to assign values to that array, since I created it as a void * array:
int mid = (begin + end) / 2;
int len = end - begin + 1;
void *pom = malloc(len*size);
But I can't assign values to that array, is there a way around it?
i = begin, j = mid + 1, k = 0;
while (i <= mid && j <= end)
**pom[k++]** = ((*comp)((char*)arr + i*size, (char *)arr + j*size) <= 0) ? arr[i] : arr[j];
while (i <= mid)
**pom[k++]** = arr[i++];
while (j <= end)
**pom[k++]** = arr[j++];
the bold lines give off an error.
Upvotes: 1
Views: 519
Reputation: 11968
Yes, you need to copy size
bytes.
So **pom[k++]** = arr[i++];
becomes memcpy(pom + size*(k++), arr+size*(i++), size);
and similar for all the others.
Upvotes: 2