Linux内核中的bsearch二分查找函数

举报
用户已注销 发表于 2021/11/19 04:00:44 2021/11/19
【摘要】 /** bsearch - binary search an array of elements* @key: pointer to item being searched for* @base: pointer to first element to search* @num: number of elements* @size: s...

  
  1. /*
  2. * bsearch - binary search an array of elements
  3. * @key: pointer to item being searched for
  4. * @base: pointer to first element to search
  5. * @num: number of elements
  6. * @size: size of each element
  7. * @cmp: pointer to comparison function
  8. *
  9. * This function does a binary search on the given array. The
  10. * contents of the array should already be in ascending sorted order
  11. * under the provided comparison function.
  12. *
  13. * Note that the key need not have the same type as the elements in
  14. * the array, e.g. key could be a string and the comparison function
  15. * could compare the string with the struct's name field. However, if
  16. * the key and elements in the array are of the same type, you can use
  17. * the same comparison function for both sort() and bsearch().
  18. */
  19. void *bsearch(const void *key, const void *base, size_t num, size_t size,
  20. int(*cmp)(const void *key, const void *elt))
  21. {
  22. size_t start = 0, end = num;
  23. int result;
  24. while (start < end) {
  25. size_t mid = start + (end - start) / 2;
  26. result = cmp(key, base + mid * size);
  27. if (result < 0)
  28. end = mid;
  29. else if (result > 0)
  30. start = mid + 1;
  31. else
  32. return (void *)base + mid * size;
  33. }
  34. return NULL;
  35. }
  36. EXPORT_SYMBOL(bsearch);

文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nameofcsdn/article/details/78139602

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。