Hey,
Long time reader, first time poster. I'm working on a project, and think that I have the logic correct, but I think that my code may have some memory errors. I'm not asking for you to give me any asnwers, but a little help in the right direction would be greatly appreciated.
void merge(void *keys, int l, int mid, int r, int size, int (*compare) (const void *, const void *))
{
char *temp =(char*)malloc((l+r)*size);
char *pkeys = (char*)keys;
int j, k;
//i = l;
j = mid + 1;
k = 0;
while(l <= mid && j <= r) {
//for (i = 0, k = 0, j = mid; i < mid && j < n;){
if(compare(&pkeys[j*size], &pkeys[l*size]) < 0) {
temp[k] = pkeys[l];
l++;
}
else {
temp[k] = pkeys[j];
j++;
}
k++;
}
//if(l > mid) {
while (j <= r) {
temp[k] = pkeys[j];
k++;
j++;
}
//}
//else {
while (l <= mid) {
temp[k] = pkeys[l];
k++;
l++;
}
//}
/* Copy temp back */
for (int i = l; i <= r; i++) {
pkeys[i] = temp[i];
}
}
void mrg_sort(void *keys, int l, int r, int size, int (*compare) (const void *, const void *))
{
int mid;
if(l < r) {
mid = (l+r)/2;
mrg_sort(keys, l, mid, size, compare);
mrg_sort(keys, (mid+1), r, size, compare);
merge(keys, l, mid, r, size, compare);
}
}
void rms_sort(void *keys, int n, int size, int (*compare) (const void *, const void *))
{
char *pkeys = (char *)keys;
mrg_sort(pkeys, 0, (n-1), size, compare);
}
Thanks