非递归方法
//二分查找法,在有序的数组中,查找target //如果找到了target,返回相应的索引index template<typename T> int binarySearch(T arr[],int n,T target){ int l=0,r=n-1; while (l<=r) { // int mid = (l+r)/2; int mid = l +(r-l)/2; //避免溢出的问题 if(arr[mid] == target) return mid; //在arr[l...mid-1]之中查找target if(target<arr[mid]) r=mid-1; else l=mid+1; } return -1; }
来源:https://www.cnblogs.com/Erick-L/p/12602837.html