bsearch 和搜索范围?
bsearch 对于直接搜索来说非常好,但是如果我需要例如搜索范围,我应该使用什么?
更新
例如,如果我想查找 a 和 b 之间的值范围 ( a >= x < b )。
更新
范围值不能相等。 因此,如果我有数组(10,20,30)并且我试图找到“15”,我想获取最接近的最小范围的地址(指针),在本例中这是范围(10,20)
bsearch is pretty good for direct search, but what should I use if I need for example search range?
update
for example if i want to find range of values between a and b ( a >= x < b ).
update
range values can be not equal.
so if i have array(10,20,30) and i'm trying to find "15" i want to get address (pointer) to minimal range that is closest, in this example this is range (10,20)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bsearch
采用的参数之一是要搜索的元素数量。因此,不要使用例如 100,而是使其在 42 中搜索...更新后
我要做的是一本手册(意味着我' d 编写代码)二分查找。
这个想法是将(剩余)数组的中间元素与下限和上限进行比较。如果较小,则在小半部分再次下限搜索;如果大于上限,则再次在大半区中搜索;否则你就找到了范围内的元素。
第二次更新后
您想返回一对指针吗?
您必须将它们包装在一个结构体中,或者将指针的地址传递给函数......或者其他东西。
但现在您有一个更简单的搜索:搜索直到找到该值(并返回 0 长度范围)或直到您即将失败。范围介于您上次查看的数组值和一侧的值之间,具体取决于您如何达到失败情况,或者如果您位于数组末尾,则为 EMPTY。
One of the parameters
bsearch
takes is the number of elements to search. So instead of, for example, 100, make it search in 42 ...After the update
What I'd do is a manual (meaning I'd write the code) binary search.
The idea is to compare the middle element of the (remaining) array to both the lower and upper limit. If it's smaller then the lower limit search again in the small half; if it's larger than the upper limit search again in the big half; otherwise you've found an element in range.
After the 2nd update
You want to return a pair of pointers?
You have to wrap them inside a struct, or pass the addresses of the pointers to the functions ... or something.
But now you have a simpler search: search until you find the value (and return a 0-length range) or until you are about to fail. The range is between the array value you last looked at and, depending on exactly how you got to the fail situation, the value to one of the sides or EMPTY if you're at the end of the array.
bsearch()
函数旨在查找匹配某些条件的单个元素。根据手册页:这里的关键是,如果有多个元素与该键匹配,则返回的元素是未指定的。所以你不知道你得到的元素是第一个、最后一个还是范围中间的某个元素。
如果您可以更改要求,以便在数组中查找 A 和 B 之间的元素,并且可以保证数组中恰好有一个 A 和一个 B,那么您可以先搜索 A,然后搜索B.
您可能必须编写自己的函数才能完全完成您想要的操作。
The
bsearch()
function is designed to find a single element matching some condition. According to the man page:The key here is that if there are multiple elements that match the key, the element returned is unspecified. So you don't know if the element you get is the first, last, or somewhere in the middle of the range.
If you can change your requirements so that you're looking for elements in the array between A and B, and you can guarantee that there is exactly one A and exactly one B in the array, then you could first search for A then search for B.
You'll probably have to write your own function to do exactly what you're wanting.