QSort.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #ifndef QSort_H
  16. #define QSort_H
  17. #include <stdbool.h>
  18. #include <stdint.h>
  19. #include <stddef.h>
  20. static inline void QSort(void* base, size_t members, size_t size,
  21. int (*compar) (const void *, const void *))
  22. {
  23. size_t i, j;
  24. size_t gap = members;
  25. uintptr_t p1, p2;
  26. bool worked;
  27. if (!members) {
  28. return;
  29. }
  30. do {
  31. gap = (gap * 10) / 13;
  32. if (gap == 9 || gap == 10) {
  33. gap = 11;
  34. } else if (gap < 1) {
  35. gap = 1;
  36. }
  37. worked = false;
  38. for (i = 0, p1 = (uintptr_t) base; i < members - gap; i++, p1 += size) {
  39. j = i + gap;
  40. p2 = (uintptr_t) base + j * size;
  41. if (compar((void *) p1, (void *) p2) > 0) {
  42. int k = size;
  43. uint8_t tmp;
  44. uint8_t* tp1;
  45. uint8_t* tp2;
  46. tp1 = (uint8_t*) p1;
  47. tp2 = (uint8_t*) p2;
  48. do {
  49. tmp = *tp1;
  50. *tp1++ = *tp2;
  51. *tp2++ = tmp;
  52. } while (--k);
  53. worked = true;
  54. }
  55. }
  56. } while (gap > 1 || worked);
  57. }
  58. #endif