在 C 中可以保证1/2 == 0
吗?我需要它来实现二进制搜索:
/*
* len is the array length
* ary is an array of ptrs
* f is a compare function
* found is a ptr to the found element in the array
* both i and offset are unsigned integers, used as indexes
*/
for(i = len/2; !found && i < len; i += offset) {
res = f(c->ary[i]);
if (res == 0) {
found = c->ary[i];
}
else {
offset = (res < 0 ? -1 : 1) * (i/2);
if (!offset) {
i = len+1;
}
}
}