如上图,二分法查找,查找的过程是先确定待查找数的范围区间,然后逐步缩小查找范围,直到找到或找不到为止。
c++代码的实现
1 #include<iostream> 2 using namespace std; 3 const int len=10; 4 int find_array(int a[],int len,int key); 5 int full_array(int a[],int len); 6 int main() 7 { 8 int i_array[len]; 9 full_array(i_array,len); 10 cout<<"input the element you want to find"<<endl; 11 int key,num; 12 cin>>key; 13 num=find_array(i_array,len,key); 14 if(num!=-1) 15 { 16 cout<<"successful find"<<i_array[num]<<endl; 17 } 18 else 19 { 20 cout<<"not the element"<<endl; 21 } 22 23 return 0; 24 } 25 26 int full_array(int *a,int len) 27 { 28 cout<<"please input "<<len<<" element init the array"<<endl; 29 int i=0; 30 while(i!=len) 31 { 32 cin>>a[i]; 33 i++; 34 } 35 return 0; 36 } 37 38 int find_array(int a[],int len,int key) 39 { 40 int low=0,high=len-1,middle; 41 while(low<high) 42 { 43 middle=(low+high)/2; 44 45 if(key==a[middle]) 46 { 47 return middle ; 48 } 49 else if(key>a[middle]) 50 { 51 low=middle+1; 52 } 53 else 54 { 55 low=middle-1; 56 } 57 58 } 59 return -1; 60 }
ok。