QSort.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #ifndef QSort_H
  16. #define QSort_H
  17. #include "util/Bits.h"
  18. #include <stdbool.h>
  19. #include <stdint.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. uint8_t tmp[size];
  43. Bits_memcpy(tmp, (void *) p1, size);
  44. Bits_memcpy((void *) p1, (void *) p2, size);
  45. Bits_memcpy((void *) p2, tmp, size);
  46. worked = true;
  47. }
  48. }
  49. } while (gap > 1 || worked);
  50. }
  51. #endif