1

Is there a 'built-in' sort, in which the int (*compar)(const void *, const void*) does not need to be specified? For example, I find that about 99% of the time I'll do either a basic ascending or descending sort and not care about a special comparison case.

Is there the equivalent of an "in-line" function that can be specified here, or is it always necessary to have a standalone function to do this comparison?

  • 1
    What do you mean by "in-line" function? – Yunnosch Sep 12 '19 at 05:41
  • Do you just want to save on typing effort, because you are so often using the same function? Methods for shortcuts would then be answer. Or do you not want to define the comparison function at all? Functions which happen to exist in standard libs and match the behaviour and prototype would then be answers. – Yunnosch Sep 12 '19 at 05:50
  • If you mean a run-time function then no, only `qsort` is available but of course you could create a library with such functions that you always link to when needed. – AndersK Sep 12 '19 at 05:55
  • Yes you write a `int compare (const void *a, const void *b) { ... }` comparison function to pass as the last argument to `qsort`. You have it return a negative value if `a` *sorts before* `b`, zero if they are equal and a positive value if `b` *sorts before* `a` (just like the `strcmp` function does for strings). `a & b` a pointers to elements in the array to be sorted. That's all there is to it. It is well worth making friends with. For integer values you can use `return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b); (which prevents potential overflow compared to `a - b`) – David C. Rankin Sep 12 '19 at 06:10

1 Answers1

0

I believe that qsort() is the only "build-in" sorting function in C. But if you write C++, std::sort() is also available.

Ryan7WU
  • 16
  • 2