blob: 495937d792db0b28db4b084e8e04592e34324a4d [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001// SPDX-License-Identifier: MIT
Mark Tomlinsonefdc2a62015-07-01 16:38:29 +12002/*
3 * This file is copyright 2001 Simon Tatham.
4 * Rewritten from original source 2006 by Dan Merillat for use in u-boot.
5 *
6 * Original code can be found at:
7 * http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
Mark Tomlinsonefdc2a62015-07-01 16:38:29 +12008 */
9
Mark Tomlinsonefdc2a62015-07-01 16:38:29 +120010#include "jffs2_private.h"
11
12int sort_list(struct b_list *list)
13{
14 struct b_node *p, *q, *e, **tail;
15 int k, psize, qsize;
16
17 if (!list->listHead)
18 return 0;
19
20 for (k = 1; k < list->listCount; k *= 2) {
21 tail = &list->listHead;
22 for (p = q = list->listHead; p; p = q) {
23 /* step 'k' places from p; */
24 for (psize = 0; q && psize < k; psize++)
25 q = q->next;
26 qsize = k;
27
28 /* two lists, merge them. */
29 while (psize || (qsize && q)) {
30 /* merge the next element */
31 if (psize == 0 ||
32 ((qsize && q) &&
33 list->listCompare(p, q))) {
34 /* p is empty, or p > q, so q next */
35 e = q;
36 q = q->next;
37 qsize--;
38 } else {
39 e = p;
40 p = p->next;
41 psize--;
42 }
43 e->next = NULL; /* break accidental loops. */
44 *tail = e;
45 tail = &e->next;
46 }
47 }
48 }
49 return 0;
50}