Skip to content

Commit e420460

Browse files
visitorckwakpm00
authored andcommitted
lib/list_sort: clarify comparison function requirements in list_sort()
Add a detailed explanation in the list_sort() kernel doc comment specifying that the comparison function must satisfy antisymmetry and transitivity. These properties are essential for the sorting algorithm to produce correct results. Issues have arisen in the past [1][2][3][4] where comparison functions violated the transitivity property, causing sorting algorithms to fail to correctly order elements. While these requirements may seem straightforward, they are commonly misunderstood or overlooked, leading to bugs. Highlighting these properties in the documentation will help prevent such mistakes in the future. Link: https://lore.kernel.org/lkml/[email protected] [1] Link: https://lore.kernel.org/lkml/[email protected] [2] Link: https://lore.kernel.org/lkml/[email protected] [3] Link: https://lore.kernel.org/lkml/[email protected] [4] Link: https://lkml.kernel.org/r/[email protected] Signed-off-by: Kuan-Wei Chiu <[email protected]> Cc: Ching-Chun (Jim) Huang <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]>
1 parent 4e0a15f commit e420460

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

lib/list_sort.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,13 @@ static void merge_final(void *priv, list_cmp_func_t cmp, struct list_head *head,
108108
* and list_sort is a stable sort, so it is not necessary to distinguish
109109
* the @a < @b and @a == @b cases.
110110
*
111+
* The comparison function must adhere to specific mathematical properties
112+
* to ensure correct and stable sorting:
113+
* - Antisymmetry: cmp(@a, @b) must return the opposite sign of
114+
* cmp(@b, @a).
115+
* - Transitivity: if cmp(@a, @b) <= 0 and cmp(@b, @c) <= 0, then
116+
* cmp(@a, @c) <= 0.
117+
*
111118
* This is compatible with two styles of @cmp function:
112119
* - The traditional style which returns <0 / =0 / >0, or
113120
* - Returning a boolean 0/1.

0 commit comments

Comments
 (0)