给出数组int arr[]={-7,3,5,8,12,16,23,33,55};
*查找target=23
#include<iostream>
using namespace std;
template<typename T>
//查找成功则返回元素下标,否则返回-1
//数组查找下标范围[begin,last)
//此二分查找算法要求数组中的元素已经按从小到大排序
int binarySearch(T arr[],int begin,int last,T val)
{
T midValue;
int midIndex;
while(begin<last)
{
midIndex=(begin+last)/2;
midValue=arr[midIndex];
if(midValue==val)
{
return midIndex; //查找成功
}
else if(midValue<val)
{
begin=midIndex+1;//重定义begin,以便继续查找[midIndex+1,last)部分
}
else
{
last=midIndex;//重定义last,以便继续查找[begin,midIndex)半部分
}
}
return -1;//查找失败
}
int main()
{
int arr[]={-7,3,5,8,12,16,23,33,55};
int index=binarySearch(arr,0,9,23);//测试查找数组范围内的元素
cout<<index<<endl;//6
int index1=binarySearch(arr,0,9,60);//测试查找超出数组右边界的元素
cout<<index1<<endl;//-1;
int index2=binarySearch(arr,0,9,-8);//测试查找超出数组左边界的元素
cout<<index2<<endl;//-1
char ch[]={'a','b','c','d'};
int index3=binarySearch(ch,0,4,'b');//测试其他数据类型的数组
cout<<index3<<endl;//1
return 0;
}