algorithm.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * algorithm.c
  3. *
  4. * Copyright (C) 2019 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as
  8. * published by the Free Software Foundation, either version 3 of the
  9. * License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "crt_priv.h"
  20. #include <string.h>
  21. void __CRT_PUBLIC(qsort)(void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*))
  22. {
  23. char *bytes = base, pivot[size], temp[size];
  24. ptrdiff_t low = 0, high = nmemb - 1;
  25. if (nmemb <= 1) return;
  26. __builtin_memcpy(pivot, &bytes[(nmemb / 2 - 1) * size], size);
  27. for (;;)
  28. {
  29. while (compare(&bytes[low * size], pivot) < 0) low++;
  30. while (compare(&bytes[high * size], pivot) > 0) high--;
  31. if (low >= high) break;
  32. __builtin_memcpy(temp, &bytes[low * size], size);
  33. __builtin_memcpy(&bytes[low * size], &bytes[high * size], size);
  34. __builtin_memcpy(&bytes[high * size], temp, size);
  35. }
  36. __CRT_PUBLIC(qsort)(bytes, high + 1, size, compare);
  37. __CRT_PUBLIC(qsort)(&bytes[(high + 1) * size], nmemb - (high + 1), size, compare);
  38. }
  39. void *__CRT_PUBLIC(bsearch)(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*))
  40. {
  41. long low = 0;
  42. long high = nmemb - 1;
  43. while (low <= high)
  44. {
  45. long mid = low + (high - low) / 2;
  46. void *current = (void*)((uintptr_t)base + mid * size);
  47. int comp = compare(current, key);
  48. if (comp < 0) low = mid + 1;
  49. else if (comp > 0) high = mid - 1;
  50. else return current;
  51. }
  52. return NULL;
  53. }