bsort.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @file bsort.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * Sorting functions.
  25. */
  26. #ifndef BADVPN_MISC_BSORT_H
  27. #define BADVPN_MISC_BSORT_H
  28. #include <stddef.h>
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <misc/debug.h>
  32. #include <misc/balloc.h>
  33. typedef int (*BSort_comparator) (const void *e1, const void *e2);
  34. static void BInsertionSort (void *arr, size_t count, size_t esize, BSort_comparator compatator, void *temp);
  35. void BInsertionSort (void *arr, size_t count, size_t esize, BSort_comparator compatator, void *temp)
  36. {
  37. ASSERT(esize > 0)
  38. for (size_t i = 0; i < count; i++) {
  39. size_t j = i;
  40. while (j > 0) {
  41. uint8_t *x = (uint8_t *)arr + (j - 1) * esize;
  42. uint8_t *y = (uint8_t *)arr + j * esize;
  43. int c = compatator(x, y);
  44. if (c <= 0) {
  45. break;
  46. }
  47. memcpy(temp, x, esize);
  48. memcpy(x, y, esize);
  49. memcpy(y, temp, esize);
  50. j--;
  51. }
  52. }
  53. }
  54. #endif