I am looking for easiest to use array sorting function in C. I am going to teach somebody little bit of C(actually these are common basics to every language). Is there any function for int arrays like Java’s
Arrays.sort(arr);
I have seen qsort, but as I saw it needs additional compare function.
So… implement the function and be done with it…
Now your lesson about sorting becomes “how does this work”?
You start by explaining memory layout and arrays. You can’t do much in C until you know this anyway.
Then you explain what a
voidpointer is and why theqsortfunction needs to know:That leads naturally to the comparison function itself… How to cast and dereference types.
Finally, if they are grasping the concepts well, you could point out that the fourth parameter to
qsortisn’t a special case. You can say it’s perfectly okay to have a pointer to a function and pass that as a parameter to another function. It’s all about the getting the type of the pointer correct, then the compiler sorts the rest out for you.