algorithm.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * algorithm.c
  3. *
  4. * Copyright (C) 2017 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 <string.h>
  20. void qsort(void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*))
  21. {
  22. void *pivot = (void*)((uintptr_t)base + (nmemb / 2) * size);
  23. void *temp = __builtin_alloca(size);
  24. if (nmemb <= 1) return;
  25. size_t low = 0;
  26. size_t high = nmemb - 1;
  27. for (;;)
  28. {
  29. while (compare((void*)((uintptr_t)base + low * size), pivot) < 0) low++;
  30. while (compare((void*)((uintptr_t)base + high * size), pivot) > 0) high--;
  31. if (low >= high) break;
  32. memcpy(temp, (void*)((uintptr_t)base + low * size), size);
  33. memcpy((void*)((uintptr_t)base + low * size), (void*)((uintptr_t)base + high * size), size);
  34. memcpy((void*)((uintptr_t)base + high * size), temp, size);
  35. }
  36. qsort(base, high, size, compare);
  37. qsort((void*)((size_t)base + high * size), nmemb - high, size, compare);
  38. }
  39. void *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. }