二分法也叫折半法
算法:当数据量很大适宜采用该方法。采用二分法查找时,数据需是排好序的。
基本思想:
假设数据是按升序排序的,对于给定值key,从序列的中间位置k开始比较,
如果当前位置arr[k]值等于key,则查找成功;
若key小于当前位置值arr[k],则在数列的前半段中查找,arr[low,mid-1];
若key大于当前位置值arr[k],则在数列的后半段中继续查找arr[mid+1,high],
直到找到为止。
时间复杂度:O(log(n))
递归算法:(c++实现)
#include<iostream>
using namespace std;
int count=0; //count统计查找次数
int binarySearch(int *arr,int low,int high,int key){
int mid=(low+high)/2; //mid代表key的位置
if(low>high){
cout<<-1<<endl; //找不到返回-1
return count;
}
count++;
if(key==arr[mid]){ //出口
cout<<mid<<endl;
return count;
}else if(key<arr[mid]){
high=mid-1;
return binarySearch(arr,low,high,key);
}else{
low=mid+1;
return binarySearch(arr,low,high,key);
}
}
int main()
{
int n;
cin>>n;
int arr[50];
int key;
//数组中n个数赋值
for(int i=0;i<n;i++)
cin>>arr[i];
cin>>key;
//0—n-1控制查找的范围
n=binarySearch(arr,0,n-1,key);
cout<<n<<endl;
return 0;
}
测试结果:
查找1 2 3 4 中 3的位置并且输出查找的次数
[查找5 找不到输出-1和查找的次数