VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)

VB爱好者乐园(VBGood)

 找回密码
 立即注册
搜索
查看: 4104|回复: 4

【备份】VC bsearch(二分查找内置函数) Demo程序

[复制链接]
 楼主| 发表于 2010-2-4 08:26:38 | 显示全部楼层 |阅读模式
本帖最后由 VBProFan 于 2010-2-4 08:29 编辑

  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #define GetElementCount(arr) (sizeof(arr) / sizeof(arr[0]))
  4. int numarray[] = {123, 145, 512, 627, 800, 933};
  5. int numeric (const int *p1, const int *p2)
  6. {
  7.     return(*p1 - *p2);
  8. }
  9. int lookup(int key)
  10. {
  11.     int *itemptr;
  12.    
  13.     // The cast of (int(*)(const void *,const void*))
  14.     // is needed to avoid a type mismatch error at compile time
  15.    
  16.     itemptr = (int *)bsearch (&key, numarray, GetElementCount(numarray),
  17.                               sizeof(int), (int(*)(const void *,const void *))numeric);
  18.     return (itemptr != NULL);
  19.    
  20. }
  21. int main(void)
  22. {
  23.     if (lookup(512))
  24.     {
  25.         printf("512 is in the table.\n");
  26.     }
  27.     else
  28.     {
  29.         printf("512 isn't in the table.\n");
  30.     }
  31.    
  32.     return 0;
  33. }

复制代码
 楼主| 发表于 2010-2-4 08:28:51 | 显示全部楼层

自编此函数

  1. void * __cdecl bsearch ( const void *key, const void *base, size_t num, size_t width, int (__cdecl *compare)(const void *, const void *) )
  2. {
  3. char *lo = (char *)base;
  4. char *hi = (char *)base + (num - 1) * width;
  5. char *mid;
  6. unsigned int half;
  7. int result;

  8. while (lo <= hi)
  9.   if (half = num / 2)
  10.   {
  11.    mid = lo + (num & 1 ? half : (half - 1)) * width;
  12.    if (!(result = (*compare)(key,mid)))
  13.     return(mid);
  14.    else if (result < 0)
  15.    {
  16.     hi = mid - width;
  17.     num = num & 1 ? half : half-1;
  18.    }
  19.    else {
  20.     lo = mid + width;
  21.     num = half;
  22.    }
  23.   }
  24.   else if (num)
  25.    return((*compare)(key,lo) ? NULL : lo);
  26.   else
  27.    break;
  28.   
  29.   return(NULL);
  30. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2010-4-20 09:14:44 | 显示全部楼层
有什么新奇特吗?
回复 支持 反对

使用道具 举报

发表于 2010-4-23 22:33:16 | 显示全部楼层
当然没有……所以是备份……

评分

参与人数 1人气 +1 收起 理由
VBProFan + 1 回答正确

查看全部评分

回复 支持 反对

使用道具 举报

发表于 2010-7-17 20:50:37 | 显示全部楼层
支持啊 楼主不错
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

文字版|手机版|小黑屋|VBGood  

GMT+8, 2023-3-22 05:41

VB爱好者乐园(VBGood)
快速回复 返回顶部 返回列表