From this link
Because this function may be optimized to use a non-linear search algorithm (presumably a binary search), the elements that compare less than key using compar should precede those that compare equal, and these should precede those that compare greater. This requirement is fulfilled by any array ordered with the same criteria used by compar (as if sorted with qsort).
- In the quoted text, what does it mean the italic part?
- Also, can I order the array descendant? or only ascendant?
- What else kind of order can the elements inside the array being sorted can it be?
The text “the elements that compare less than key using compar should precede those that compare equal, and these should precede those that compare greater” means that if you have two elements of the array, say
a[i]anda[j], andcomparreportsa[i]is “less than”a[j], thenishould be less thanj(by their integer values), and, ifcomparreportsa[i]is “greater than”a[j], thenishould be greater thanj. In other words, the relationship between the positions of the elements in the array matches the relationship between their values as reported bycompar.(Note that these words only tell you about the ordering for elements that
comparreports as less than or greater than. It does not impose any constraint on ordering for elements thatcomparreports as equal.)The
comparfunction defines what the ordering is. You may have some notion in your head that 3 < 4 or “apple” is before “banana”, butcomparcan be any ordering. For this purpose, “ascending” means progress in the order defined; it does not mean necessarily 3 before 4 or “apple” before “banana”. You could, for example, sort integers according to their low bits first, then their second lowest bits, then their third lowest bits, and so on, instead of by their usual values.Any total ordering can be used. A total ordering gives one relationship between any two elements (<, =, or >) and does not contain any “contradictions” to putting the elements in order. Formally, for any x, y, and z, a total ordering satisfies: x ≤ y and y ≤ x implies x = y, x ≤ y and y ≤ z implies x ≤ z, and either x ≤ y or y ≤ x.
Any relationship that satisfies those requirements can be used.