qsort.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #include <exports.h>
  18. void qsort(void *base,
  19. size_t nel,
  20. size_t width,
  21. int (*comp)(const void *, const void *))
  22. {
  23. size_t wgap, i, j, k;
  24. char tmp;
  25. if ((nel > 1) && (width > 0)) {
  26. assert(nel <= ((size_t)(-1)) / width); /* check for overflow */
  27. wgap = 0;
  28. do {
  29. wgap = 3 * wgap + 1;
  30. } while (wgap < (nel-1)/3);
  31. /* From the above, we know that either wgap == 1 < nel or */
  32. /* ((wgap-1)/3 < (int) ((nel-1)/3) <= (nel-1)/3 ==> wgap < nel. */
  33. wgap *= width; /* So this can not overflow if wnel doesn't. */
  34. nel *= width; /* Convert nel to 'wnel' */
  35. do {
  36. i = wgap;
  37. do {
  38. j = i;
  39. do {
  40. register char *a;
  41. register char *b;
  42. j -= wgap;
  43. a = j + ((char *)base);
  44. b = a + wgap;
  45. if ((*comp)(a, b) <= 0) {
  46. break;
  47. }
  48. k = width;
  49. do {
  50. tmp = *a;
  51. *a++ = *b;
  52. *b++ = tmp;
  53. } while (--k);
  54. } while (j >= wgap);
  55. i += width;
  56. } while (i < nel);
  57. wgap = (wgap - width)/3;
  58. } while (wgap);
  59. }
  60. }
  61. int strcmp_compar(const void *p1, const void *p2)
  62. {
  63. return strcmp(*(const char **)p1, *(const char **)p2);
  64. }