1.二分查找是常用的编程方法,请用完整代码实现该函数(不许调用库函数)
void *bsearch(const void *key, const void *base, size_t nel, size_t
width, int (*compar) (const void *, const void *));
参考答案
:
二分查找完整代码:
#include<iostream>
using namespace std;
void * bsearch(const void *key, const void *base, size_t nel, size_t
width, int (*cmp)(const void *, const void *)){
????void *mid = NULL;
????int sign;
????while (nel > 0) {
????????
????????mid = (char *)base + width*(nel/2);
????????sign = cmp(key, mid);
????????if (sign == 0) return mid;//找到?
????????if (nel == 1) break;
????????else if (sign < 0)
????????????nel /= 2;//下取整?
????????else {
????????????base = mid;
????????????nel -= nel/2;//上取整?
????????}
????????
????}
????return NULL;
本内容试读结束,登录后可阅读更多
下载后可阅读完整内容,剩余4页未读,立即下载