注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Mr.Right

不顾一切的去想,于是我们有了梦想。脚踏实地的去做,于是梦想成了现实。

 
 
 

日志

 
 
关于我

人生一年又一年,只要每年都有所积累,有所成长,都有那么一次自己认为满意的花开时刻就好。即使一时不顺,也要敞开胸怀。生命的荣枯并不是简单的重复,一时的得失不是成败的尺度。花开不是荣耀,而是一个美丽的结束,花谢也不是耻辱,而是一个低调的开始。

网易考拉推荐

阿英讲二分法查找C语言实现  

2016-12-09 21:02:16|  分类: 编程 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
// The code below assumes that the input numbers are in ascending order. It can only be used for sorted arrays, but it's fast as compared to linear search.
#include <stdio.h>
 
int main()
{
   int first, last, middle, n, search;
 int array[] = {5,7,9,11,13,17,24,47,68,72,89,90,112};
 
 search = 17;
  n = sizeof(array)/sizeof(array[0]);
   first = 0;
   last = n - 1;
   middle = (first+last)/2; // step 1: Guess the average location
 
   while (first <= last) {
  // step 2: test
      if (array[middle] < search)  // If the guess was too low, set "first" to be one larger than the guess
         first = middle + 1;   
      else if (array[middle] == search) { // If you guessed the location, stop. You found it!
         printf("%d found at location %d.\n", search, middle+1);
         break;      }
   else   // array[middle] > search,   If the guess was too high, set "last" to be one smaller than the guess.
       last = middle - 1;
  
  // step3: go back to step 1
       middle = (first + last)/2;
   }
   if (first > last)
      printf("Not found! %d is not present in the list.\n", search);
 
   return 0;  
}




///////////////////////////////////////////////////////////////////////

// The code below assumes that the input numbers are in ascending order. It can only be used for sorted arrays, but it's fast as compared to linear search. 
#include <stdio.h>
 
int main()
{
   int first, last, middle, n, search;
int array[] = {5,7,9,11,13,17,24,47,68,72,89,90,112};
 
search = 72;

  n = sizeof(array)/sizeof(array[0]);

     for (first = 0, last = n - 1; first <= last; ) {
middle = (first+last)/2; // step 1: Guess the average location
// step 2: test
      if (array[middle] < search)  // If the guess was too low, set "first" to be one larger than the guess
         first = middle + 1;    
      else if (array[middle] > search)//If the guess was too high, set "last" to be one smaller than the guess.
       last = middle - 1;
else if (array[middle] == search) { // If you guessed the location, stop. You found it!
printf("%d found at location %d.\n", search, middle+1);
break;}
  }

   if (first > last)
      printf("Not found! %d is not present in the list.\n", search);
 
   return 0;   
}
  评论这张
 
阅读(117)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017