二分查找
非递归
#include <iostream> #include<cstdlib> #include<cstring> using namespace std; int bin_search(int a[],int low,int high,int des){ int mid; if(a!=NULL&&(low<high)){ while(low<=high){ mid=(low+high)/2; if(a[mid]==des){ return mid; } else if(a[mid]>des){ high=mid-1; } else low=mid+1; } } return -1; } int main() { int a[]={1,2,3,4,5,6,7,8,9}; int low=0; int high=sizeof(a)/sizeof(*a)-1; cout<<bin_search(a,low,high,5); return 0; }
递归
#include <iostream> #include<cstdlib> #include<cstring> using namespace std; int bin_search(int a[],int low,int high,int des){ int mid; if(a!=NULL&&(low<high)){ while(low<=high){ mid=(low+high)/2; if(a[mid]==des){ return mid; } else if(a[mid]>des){ high=mid-1; } else low=mid+1; } } return -1; } int main() { int a[]={1,2,3,4,5,6,7,8,9}; int low=0; int high=sizeof(a)/sizeof(*a)-1; cout<<bin_search(a,low,high,5); return 0; }