二分法查找

#include<stdio.h>
#include<stdlib.h>

//二分法查找 
int binary_search(int* array,int n,int key)
{
 int low=0;
 int high=n-1;
 int mid;
 
 if(high < low)
 return -1;
 
 while(low <= high)
 {
  mid=low+((high-low)>>1);
  if(array[mid] == key){
   return mid;
  }
  else{
   if(array[mid] > key)
   {
   high = mid-1; 
   }else
   {
    low = mid+1;
   }
  }
 }
 if(low > high)
 return -1;
}

int main()
{
 int array[]={1,2,3,4,5,6,7,8,9};
 int result=binary_search(array,9,6);
 if(result==-1)
 printf("Not Found!");
 else
 printf("您所查找的数的标号为:array[%d]\n",result);
 return 0;
 
}

​

  

posted @ 2016-04-08 18:42  boer儿  阅读(168)  评论(0编辑  收藏  举报