Guys I'm having trouble implementing my generic insertion sort. That first thing I noticed was that I was comparing negative numbers because I was using a char ptr which obviously could not point to numbers that are huge. So then I opted for a void * but even that was not enough.
Here are the three main functions in question.
Code:
void insertion_sort(void *base, size_t nitems, size_t memSize, int (*cmp)(const void *, const void *))
{
char *carray = (char *)base;
void *tmp;
unsigned int i;
for(i = 1; i < nitems; i++)
{
int j;
tmp = &carray[i * memSize];
for(j = i; j >= 1 && cmp(&carray[(j - 1) * memSize], tmp) > 0; j--)
{
Swap(&carray[(j - 1) * memSize], tmp, memSize);
}
}
}
int cmp(const void *a, const void *b)
{
const int *A = a, *B = b;
printf("%d %d\n", *A, *B);
return (*A > *B) - (*A < *B);
}
void Swap(void *a, void *b, size_t memSize)
{
char tmp;
char *aa = a, *bb = b;
do
{
tmp = *aa;
*aa++ = *bb;
*bb++ = tmp;
}
while(--memSize > 0);
}