二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。时间复杂度为O(logN)
二分查找就是将查找的键和子数组的中间键作比较,如果被查找的键小于中间键,就在左子数组继续查找;
如果大于中间键,就在右子数组中查找,否则中间键就是要找的元素。
二分查找可以用递归方式或非递归方式实现;
#include <iostream>
#define MAX 100
using namespace std;
int binary_search(int a[], int nLength, int key)
{
int left = 0;
int right =nLength -1;
while(left<= right)
{
int mid = (left+right)/2;
if (a[mid]== key)
return mid;
else if(a[mid]> key)
right =mid-1;
else if(a[mid]< key)
left = mid+1;
}
return -1;
} //非递归方式
int bin_search(int b[],int left, int right, int key)
{
while(left <= right)
{
int mid = (left+right)/2;
if (b[mid]== key)
return mid;
else if (b[mid]>key)
return bin_search(b,left,mid-1,key);
else if (b[mid]<key)
return bin_search(b,mid+1,right,key);
}
return -1; //递归方法
}
int main()
{
int a[]={0,1,2,3,4,5,6,7,8,9};
int key= 5;
int res1 =binary_search(a,sizeof(a)/sizeof(int),key) +1; //目标5的位置
cout<<"key的位置为"<<res1<<endl;
//system("pause");
cout<<"换种方法,按enter键继续"<<endl;
cin.get();
int res2 = bin_search(a,0,sizeof(a)/sizeof(int)-1,key) +1;
cout<<"key的位置为"<<res2<<endl;
}
另外二分查找还有一些变种;例如
查找第一个与key相等的元素等,参考二分查找的一些变种。