I implemented a generic insertion sort routine that can sort an array of any type. It's similar to the qsort function from the standard library. My goal it to optimize the code for readability above everything else, so I would appreciate any feedback.
void isort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) {
for (size_t i = 1; i < nmemb; i++) {
char *key = (char *)base + i * size;
char key_copy[size];
memcpy(key_copy, key, size);
char *curr = NULL;
for (curr = key; curr > base && compar(curr - size, key_copy) > 0; curr -= size) {
memcpy(curr, curr - size, size);
}
memcpy(curr, key_copy, size);
}
}
Example client code:
int cmp_int(const void *p, const void *q) {
return *(int *)p - *(int *)q;
}
int main(void) {
int arr[] = { 4, 2, 3, 0, 2, 5 };
size_t nelem = sizeof(arr) / sizeof(arr[0]);
isort(arr, nelem, sizeof(arr[0]), cmp_int);
for (size_t i = 0; i < nelem; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}