Is there any way I can modify the input or manupulate the bits of
input to memcmp so that it can compare with negative integers too?
Corresponding signed and unsigned integer types have the same size and consistent representation. You cannot tell from the representation of an integer alone whether to interpret it as signed or unsigned, and you need to compare differently to sort as signed numbers than you do to sort as unsigned numbers.
You could modify inputs of signed types, type-specifically, so that you can sort them as unsigned numbers, then convert back after sorting. For type int, that might look like so:
void mergesort_int(int* arr, size_t n) {
unsigned int *uarr = (unsigned int *)arr;
for (size_t i = 0; i < n; i++) {
*uarr -= (unsigned int) INT_MIN;
}
mergesort(uarr, n, sizeof *uarr);
for (size_t i = 0; i < n; i++) {
*uarr += (unsigned int) INT_MIN;
}
}
But such conversions are type-specific, so you will need one for each supported signed type. And this is not going to be all in one function, unless that function is a godawful ugly mess.
Additionally, you need to account for byte order. That could be layered on top of the above as a conversion to and from big-endian byte order, but that only makes the mess worse.
I do not wish to pass a function as a paramter or use if-else to
determine the data type from the size and use different cases for
different data types.
Mick Jagger has some sage advice for you: "You can't always get what you want."
There is a good reason why the standard library's qsort() takes a comparison function as an argument. Different data types do not have similar enough representation to compare consistently via a single, universal function. Even restricting to integer types is not sufficient for that. On a big-endian machine, you might get away with a universal comparison function for unsigned integer types only, but even that does not work on a little-endian machine if you're looking for numeric order.
Passing a comparison function is the cleanest approach I know of.
qsortfunction does, because there's really no other way to do a generic comparison otherwise. Think for example about sorting an array of structures, where only one member of the structure is relevant for the ordering. If you usememcmpyou will use the whole structure, and all of its members plus eventual padding which will contain indeterminate data.memcmp()doen't seem to be the right tool for the job when there is an array ofstruct.memcmp()also is not the right tool for the job when sorting integers larger than one byte, as the result will depend on byte order, which is likely undesirable. You're probably on a little-endian machine. In that case, try sorting a collection of positiveints having a wide range of values, such that they don't all fit in a single byte.negative integers, yetcharis signed or unsigned, depending on an implementation detail.