qsort.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Code adapted from uClibc-0.9.30.3
  3. *
  4. * It is therefore covered by the GNU LESSER GENERAL PUBLIC LICENSE
  5. * Version 2.1, February 1999
  6. *
  7. * Wolfgang Denk <wd@denx.de>
  8. */
  9. /* This code is derived from a public domain shell sort routine by
  10. * Ray Gardner and found in Bob Stout's snippets collection. The
  11. * original code is included below in an #if 0/#endif block.
  12. *
  13. * I modified it to avoid the possibility of overflow in the wgap
  14. * calculation, as well as to reduce the generated code size with
  15. * bcc and gcc. */
  16. #include <linux/types.h>
  17. #if 0
  18. #include <assert.h>
  19. #else
  20. #define assert(arg)
  21. #endif
  22. void qsort(void *base,
  23. size_t nel,
  24. size_t width,
  25. int (*comp)(const void *, const void *))
  26. {
  27. size_t wgap, i, j, k;
  28. char tmp;
  29. if ((nel > 1) && (width > 0)) {
  30. assert(nel <= ((size_t)(-1)) / width); /* check for overflow */
  31. wgap = 0;
  32. do {
  33. wgap = 3 * wgap + 1;
  34. } while (wgap < (nel-1)/3);
  35. /* From the above, we know that either wgap == 1 < nel or */
  36. /* ((wgap-1)/3 < (int) ((nel-1)/3) <= (nel-1)/3 ==> wgap < nel. */
  37. wgap *= width; /* So this can not overflow if wnel doesn't. */
  38. nel *= width; /* Convert nel to 'wnel' */
  39. do {
  40. i = wgap;
  41. do {
  42. j = i;
  43. do {
  44. register char *a;
  45. register char *b;
  46. j -= wgap;
  47. a = j + ((char *)base);
  48. b = a + wgap;
  49. if ((*comp)(a, b) <= 0) {
  50. break;
  51. }
  52. k = width;
  53. do {
  54. tmp = *a;
  55. *a++ = *b;
  56. *b++ = tmp;
  57. } while (--k);
  58. } while (j >= wgap);
  59. i += width;
  60. } while (i < nel);
  61. wgap = (wgap - width)/3;
  62. } while (wgap);
  63. }
  64. }