mergesort.c 1.1 KB

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