bsearch.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * A generic implementation of binary search for the Linux kernel
  3. *
  4. * Copyright (C) 2008-2009 Ksplice, Inc.
  5. * Author: Tim Abbott <tabbott@ksplice.com>
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; version 2.
  10. */
  11. #include <linux/module.h>
  12. #include <linux/bsearch.h>
  13. /*
  14. * bsearch - binary search an array of elements
  15. * @key: pointer to item being searched for
  16. * @base: pointer to first element to search
  17. * @num: number of elements
  18. * @size: size of each element
  19. * @cmp: pointer to comparison function
  20. *
  21. * This function does a binary search on the given array. The
  22. * contents of the array should already be in ascending sorted order
  23. * under the provided comparison function.
  24. *
  25. * Note that the key need not have the same type as the elements in
  26. * the array, e.g. key could be a string and the comparison function
  27. * could compare the string with the struct's name field. However, if
  28. * the key and elements in the array are of the same type, you can use
  29. * the same comparison function for both sort() and bsearch().
  30. */
  31. void *bsearch(const void *key, const void *base, size_t num, size_t size,
  32. int (*cmp)(const void *key, const void *elt))
  33. {
  34. size_t start = 0, end = num;
  35. int result;
  36. while (start < end) {
  37. size_t mid = start + (end - start) / 2;
  38. result = cmp(key, base + mid * size);
  39. if (result < 0)
  40. end = mid;
  41. else if (result > 0)
  42. start = mid + 1;
  43. else
  44. return (void *)base + mid * size;
  45. }
  46. return NULL;
  47. }
  48. EXPORT_SYMBOL(bsearch);