qsort.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* -*-comment-start: "//";comment-end:""-*-
  2. * GNU Mes --- Maxwell Equations of Software
  3. * Copyright © 2017,2018 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  4. *
  5. * This file is part of GNU Mes.
  6. *
  7. * GNU Mes is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or (at
  10. * your option) any later version.
  11. *
  12. * GNU Mes is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with GNU Mes. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <stdlib.h>
  21. #include <string.h>
  22. void
  23. qswap (void *a, void *b, size_t size)
  24. {
  25. char *buf[8];
  26. memcpy (buf, a, size);
  27. memcpy (a, b, size);
  28. memcpy (b, buf, size);
  29. }
  30. size_t
  31. qpart (void *base, size_t count, size_t size, int (*compare) (void const *, void const *))
  32. {
  33. void *p = base + count * size;
  34. size_t i = 0;
  35. for (size_t j = 0; j < count; j++)
  36. {
  37. int c = compare (base + j * size, p);
  38. if (c < 0)
  39. {
  40. #if 1 //__x86_64__
  41. qswap (base + i * size, base + j * size, size);
  42. #else
  43. int p1 = base + i * size;
  44. int p2 = base + j * size;
  45. qswap (p1, p2, size);
  46. #endif
  47. i++;
  48. }
  49. else if (c == 0)
  50. i++;
  51. }
  52. if (compare (base + count * size, base + i * size) < 0)
  53. qswap (base + i * size, base + count * size, size);
  54. return i;
  55. }
  56. void
  57. qsort (void *base, size_t count, size_t size, int (*compare) (void const *, void const *))
  58. {
  59. if (count > 1)
  60. {
  61. int p = qpart (base, count - 1, size, compare);
  62. qsort (base, p, size, compare);
  63. #if 1 //__x86_64__
  64. qsort (base + p * size, count - p, size, compare);
  65. #else
  66. int p1 = base + p * size;
  67. int p2 = count - p;
  68. qsort (p1, p2, size, compare);
  69. #endif
  70. }
  71. }