]>
git.ipfire.org Git - thirdparty/xfsprogs-dev.git/blob - libfrog/list_sort.c
1 /* List sorting code from Linux::lib/list_sort.c. */
6 #define unlikely(x) (x)
7 #define MAX_LIST_LENGTH_BITS 20
10 * Returns a list organized in an intermediate format suited
11 * to chaining of merge() calls: null-terminated, no reserved or
12 * sentinel head node, "prev" links not maintained.
14 static struct list_head
*merge(void *priv
,
15 int (*cmp
)(void *priv
, struct list_head
*a
,
17 struct list_head
*a
, struct list_head
*b
)
19 struct list_head head
, *tail
= &head
;
22 /* if equal, take 'a' -- important for sort stability */
23 if ((*cmp
)(priv
, a
, b
) <= 0) {
37 * Combine final list merge with restoration of standard doubly-linked
38 * list structure. This approach duplicates code from merge(), but
39 * runs faster than the tidier alternatives of either a separate final
40 * prev-link restoration pass, or maintaining the prev links
43 static void merge_and_restore_back_links(void *priv
,
44 int (*cmp
)(void *priv
, struct list_head
*a
,
46 struct list_head
*head
,
47 struct list_head
*a
, struct list_head
*b
)
49 struct list_head
*tail
= head
;
53 /* if equal, take 'a' -- important for sort stability */
54 if ((*cmp
)(priv
, a
, b
) <= 0) {
69 * In worst cases this loop may run many iterations.
70 * Continue callbacks to the client even though no
71 * element comparison is needed, so the client's cmp()
72 * routine can invoke cond_resched() periodically.
74 if (unlikely(!(++count
)))
75 (*cmp
)(priv
, tail
->next
, tail
->next
);
77 tail
->next
->prev
= tail
;
86 * list_sort - sort a list
87 * @priv: private data, opaque to list_sort(), passed to @cmp
88 * @head: the list to sort
89 * @cmp: the elements comparison function
91 * This function implements "merge sort", which has O(nlog(n))
94 * The comparison function @cmp must return a negative value if @a
95 * should sort before @b, and a positive value if @a should sort after
96 * @b. If @a and @b are equivalent, and their original relative
97 * ordering is to be preserved, @cmp must return 0.
99 void list_sort(void *priv
, struct list_head
*head
,
100 int (*cmp
)(void *priv
, struct list_head
*a
,
101 struct list_head
*b
))
103 struct list_head
*part
[MAX_LIST_LENGTH_BITS
+1]; /* sorted partial lists
104 -- last slot is a sentinel */
105 int lev
; /* index into part[] */
107 struct list_head
*list
;
109 if (list_empty(head
))
112 memset(part
, 0, sizeof(part
));
114 head
->prev
->next
= NULL
;
118 struct list_head
*cur
= list
;
122 for (lev
= 0; part
[lev
]; lev
++) {
123 cur
= merge(priv
, cmp
, part
[lev
], cur
);
127 if (unlikely(lev
>= ARRAY_SIZE(part
)-1)) {
135 for (lev
= 0; lev
< max_lev
; lev
++)
137 list
= merge(priv
, cmp
, part
[lev
], list
);
139 merge_and_restore_back_links(priv
, cmp
, head
, part
[max_lev
], list
);