Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

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/20240701205639.117194-1-visitorckw@gmail.com [1]
Link: https://lore.kernel.org/lkml/20241203202228.1274403-1-visitorckw@gmail.com [2]
Link: https://lore.kernel.org/lkml/20241209134226.1939163-1-visitorckw@gmail.com [3]
Link: https://lore.kernel.org/lkml/20241209145728.1975311-1-visitorckw@gmail.com [4]
Link: https://lkml.kernel.org/r/20250106170104.3137845-3-visitorckw@gmail.com
Signed-off-by: Kuan-Wei Chiu <visitorckw@gmail.com>
Cc: Ching-Chun (Jim) Huang <jserv@ccns.ncku.edu.tw>
Cc: <chuang@cs.nycu.edu.tw>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>

authored by

Kuan-Wei Chiu and committed by
Andrew Morton
e420460b 4e0a15f8

+7
+7
lib/list_sort.c
··· 108 108 * and list_sort is a stable sort, so it is not necessary to distinguish 109 109 * the @a < @b and @a == @b cases. 110 110 * 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 + * 111 118 * This is compatible with two styles of @cmp function: 112 119 * - The traditional style which returns <0 / =0 / >0, or 113 120 * - Returning a boolean 0/1.