标签:int out 下标 cin ret str 递归 using 循环
算法复杂度为while循环的个数
缺点是待查表为有序表
1 #include <iostream> 2 3 using namespace std; 4 int binary_search(int *a,int len,int target); 5 int main() 6 { 7 size_t LEN=5000; 8 int a[LEN],target,index; 9 for(size_t i=0; i<LEN; i++) 10 a[i]=i-2500; //升序排列 11 cin>>target; 12 index=binary_search(a,LEN,target); 13 if(index!=-1) 14 cout<<"数组下标为"<<index<<endl; 15 else 16 cout<<"没有找到"<<endl; 17 return 0; 18 } 19 int binary_search(int *a,int len,int target) 20 { 21 int low,mid,heigh; 22 low=0; 23 heigh=len-1; 24 mid=len/2; 25 while(low<=heigh) 26 { 27 if(a[mid]==target) 28 return mid; 29 if(a[mid]>target) 30 heigh=mid-1; 31 if(a[mid]<target) 32 low=mid+1; 33 mid=low+(heigh-low)/2; 34 } 35 return -1; 36 }
也可以用递归的
1 #include <iostream> 2 3 using namespace std; 4 int binary_search(int *a,int low,int mid,int heigh,int target); 5 int main() 6 { 7 size_t LEN=5000; 8 int a[LEN],target,index; 9 for(size_t i=0;i<LEN;i++) 10 a[i]=i-2500; //升序排列 11 cin>>target; 12 index=binary_search(a,0,LEN/2,LEN-1,target); 13 if(index!=-1) 14 cout<<"数组下标为"<<index<<endl; 15 else 16 cout<<"没有找到"<<endl; 17 return 0; 18 } 19 int binary_search(int *a,int low,int mid,int heigh,int target) 20 { 21 if(low>heigh) 22 return -1; 23 if(a[mid]==target) 24 return mid; 25 else if(a[mid]>target) 26 return binary_search(a,low,low+(mid-1-low)/2,mid-1,target); 27 else if(a[mid]<target) 28 return binary_search(a,mid+1,mid+1+(heigh-mid-1)/2,heigh,target); 29 }
望多多指教
标签:int out 下标 cin ret str 递归 using 循环
原文地址:http://www.cnblogs.com/hyacinthhome/p/6347970.html