Chinaunix首页 | 论坛 | 博客
  • 博客访问: 676401
  • 博文数量: 156
  • 博客积分: 6010
  • 博客等级: 准将
  • 技术积分: 1201
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-05 20:08
文章分类

全部博文(156)

文章存档

2010年(13)

2008年(39)

2007年(104)

我的朋友

分类: C/C++

2007-06-12 00:03:09

2分查找法,嘿嘿

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */
   int binsearch(int x, int v[], int n)
   {
       int low, high, mid;

       low = 0;
       high = n - 1;
       while (low <= high) {
           mid = (low+high)/2;
           if (x < v[mid])
               high = mid + 1;
           else if (x > v[mid])
               low = mid + 1;
           else /* found match */
               return mid;
       }
       return -1; /* no match */
   }

这个用了2个test,下面使用一个test

/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] ; 2ed version */
   int binsearch(int x, int v[], int n)
   {
       int low, high, mid;

       low = 0;
       high = n - 1;
       while (low <= high) {
           mid = (low+high)/2;
           if ( x != v[mid]
        (x < v[mid]) ? (high = mid + 1) : (low = mid + 1);
           else /* found match */
               return mid;
       }
       return -1; /* no match */
   }

阅读(1748) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~