algorithm.h 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #pragma once
  2. #include <stdbool.h>
  3. #include "pocketpy/common/utils.h"
  4. #define c11__less(a, b) ((a) < (b))
  5. #define c11__lower_bound(T, ptr, count, key, less, out_index) \
  6. do { \
  7. T* __first = ptr; \
  8. int __len = count; \
  9. while(__len >= 8) { \
  10. int __l2 = __len >> 1; \
  11. T* __m = __first + __l2; \
  12. if(less((*__m), (key))) { \
  13. __first = ++__m; \
  14. __len -= __l2 + 1; \
  15. } else { \
  16. __len = __l2; \
  17. } \
  18. } \
  19. switch(__len) { \
  20. case 7: \
  21. if(less(*__first, (key))) __first++; \
  22. case 6: \
  23. if(less(*__first, (key))) __first++; \
  24. case 5: \
  25. if(less(*__first, (key))) __first++; \
  26. case 4: \
  27. if(less(*__first, (key))) __first++; \
  28. case 3: \
  29. if(less(*__first, (key))) __first++; \
  30. case 2: \
  31. if(less(*__first, (key))) __first++; \
  32. case 1: \
  33. if(less(*__first, (key))) __first++; \
  34. case 0: break; \
  35. default: c11__unreachable(); \
  36. } \
  37. *(out_index) = __first - (T*)(ptr); \
  38. } while(0)
  39. /**
  40. * @brief Sorts an array of elements of the same type, using the given comparison function.
  41. * @param ptr Pointer to the first element of the array.
  42. * @param count Number of elements in the array.
  43. * @param elem_size Size of each element in the array.
  44. * @param cmp Comparison function that takes two elements and returns an integer similar to
  45. * `strcmp`.
  46. */
  47. bool c11__stable_sort(void* ptr,
  48. int length,
  49. int elem_size,
  50. int (*f_lt)(const void* a, const void* b, void* extra),
  51. void* extra);
  52. int c11__bit_length(unsigned long x);