algorithm.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #pragma once
  2. #include <stdbool.h>
  3. #define c11__less(a, b) ((a) < (b))
  4. #define c11__lower_bound(T, ptr, count, key, less, out_index) \
  5. do { \
  6. T* __first = ptr; \
  7. int __len = count; \
  8. while(__len > 8) { \
  9. int __l2 = __len >> 1; \
  10. T* __m = __first + __l2; \
  11. if(less((*__m), (key))) { \
  12. __first = ++__m; \
  13. __len -= __l2 + 1; \
  14. } else { \
  15. __len = __l2; \
  16. } \
  17. } \
  18. while(__len && less(*__first, (key))) { \
  19. ++__first; \
  20. --__len; \
  21. } \
  22. *(out_index) = __first - (T*)(ptr); \
  23. } while(0)
  24. /**
  25. * @brief Sorts an array of elements of the same type, using the given comparison function.
  26. * @param ptr Pointer to the first element of the array.
  27. * @param count Number of elements in the array.
  28. * @param elem_size Size of each element in the array.
  29. * @param cmp Comparison function that takes two elements and returns an integer similar to
  30. * `strcmp`.
  31. */
  32. bool c11__stable_sort(void* ptr,
  33. int count,
  34. int elem_size,
  35. int (*f_lt)(const void* a, const void* b, void* extra),
  36. void* extra);