C编程 - 二进制搜索

时间:2016-03-25 23:28:25

标签: c search binary

#include <stdio.h>

int main(void)
{

 int array[]={1,2,3,4,5,6,7,8,9,10};
 int size = 10;
 int number = 3;
 int min = 0;
 int max = size -1;


 int g = (min + max) / 2;
 while(g > 0)
 {
   if(array[g] == number)
   {
   printf("found number: %i\n", array[g]);
   return true;
   }
   else if(array[g] < number)
   {
   printf("middle point %i is lower than number %i\n", array[g], number);
   min = g/2 + 1;
   return min;
   }
   else if (array[g] > number)
   {
   printf("middle point %i is higher than number\n", array[g]);
   max = g/2 - 1;
   return max;
   }
 }
}

是否可以更改int值,即使它超出范围?或者我必须采取完全不同的方法吗?

0 个答案:

没有答案