#include<stdio.h> //查找成功则返回所在下标否则返回-1 int binsearch(int A[], int n,int a) { int low, high, mid; low = 0; high = n -1; while ( low <= high) { /// 这里必须是 <= mid = (low+high) / 2; if (A[mid] == a) return mid; else if(A[mid]<a) low = mid +1; else high=mid-1; } return -1; } int main() { int a[]={1,2,44,44,99}; printf("%d",binsearch(a,5,44)); }
//二分查找,递归算法 #include <iostream> #include<stdio.h> using namespace std; int binSearch(int a[],int low,int high,int b) { int mid = (high-low)/2; if(a[mid] == b) return mid; if(a[mid] > b) binSearch(a,low,mid-1,b); if(a[mid] < b) binSearch(a,mid+1,high,b); } int main() { int a[] = {2,6,8,88888,88888888}; int yy; yy = binSearch(a,0,4,8); printf("%d",yy); return 0; }