algorithm.h 2.2 KB

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