在读了redis和sqlite的源码之后,不知不觉就被其中任意操作某个字节的思想感染了,同时为了效率,平时写的代码也喜欢用C语言,C语言经常重复的写二分查找,对于不同的元素得重复的写,于是打算像C++ STL那样写一个泛型的二分查找,以后再需要二分查找的时候就不用重复实现,重复调试了,在此做记录
如果查找不存在将返回查找目标值应该插入的位置
//compare返回1取后半段,返回-1取前半段,返回0代表相等
int binarySearch(void *data, void *target, size_t offset, size_t size, int(*compare)(void *x, void *y)){
int begin = 0, end = size - 1, mid = (begin + end) / 2;
while(begin <= end){
if(compare((char *)data + offset * mid, target) == 0)
return mid;
else if(compare((char *)data + offset * mid, target) < 0)
end = mid - 1;
else
begin = mid + 1;
mid = (begin + end) / 2;
if(end < 0)
return 0;
}
return begin;
}
int compare(void *x, void *y){
if(*(int *)x == *(int *)y){
return 0;
}else if(*(int *)x > *(int *)y){
return -1;
}else{
return 1;
}
}
struct dataGroup{
int a;
int b;
};
int main(){
dataGroup data[] = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}};
int target = 10;
printf("%d\n", binarySearch(data, &target, sizeof(dataGroup), sizeof(data) / sizeof(dataGroup), compare));
}