注册 登录
  • 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言基础:二分查找法示范代码

OC/C/C++ 水墨上仙 2948次浏览 已收录 手机上查看

C语言基础:二分查找法演示代码

#include <stdio.h>
int binary_search(int array[], int value, int size)
 {
   int found = 0;
   int high = size, low = 0, mid;
   mid = (high + low) / 2;
   printf("\n\nLooking for %d\n", value);
   while ((! found) && (high >= low))
    {
      printf("Low %d Mid %d High %d\n", low, mid, high);
      if (value == array[mid])
        found = 1;
      else if (value < array[mid])
        high = mid - 1;
      else
        low = mid + 1;
      mid = (high + low) / 2;
   }
  return((found) ? mid: -1);
 }
int main(void)
 {
   int array[100], i;
   for (i = 0; i < 100; i++)
     array[i] = i;
   printf("Result of search %d\n", binary_search(array, 33, 100));
   printf("Result of search %d\n", binary_search(array, 75, 100));
   printf("Result of search %d\n", binary_search(array, 1, 100));
   printf("Result of search %d\n", binary_search(array, 1001, 100));
return 1;
 }
  

输出结果

Looking for 33
Low 0 Mid 50 High 100
Low 0 Mid 24 High 49
Low 25 Mid 37 High 49
Low 25 Mid 30 High 36
Low 31 Mid 33 High 36
Result of search 33
Looking for 75
Low 0 Mid 50 High 100
Low 51 Mid 75 High 100
Result of search 75
Looking for 1
Low 0 Mid 50 High 100
Low 0 Mid 24 High 49
Low 0 Mid 11 High 23
Low 0 Mid 5 High 10
Low 0 Mid 2 High 4
Low 0 Mid 0 High 1
Low 1 Mid 1 High 1
Result of search 1
Looking for 1001
Low 0 Mid 50 High 100
Low 51 Mid 75 High 100
Low 76 Mid 88 High 100
Low 89 Mid 94 High 100
Low 95 Mid 97 High 100
Low 98 Mid 99 High 100
Low 100 Mid 100 High 100
Result of search -1
   


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言基础:二分查找法示范代码
喜欢 (0)
[开心洋葱]
分享 (0)
关于作者:
水墨上仙
……
加载中……