二分查找分C++实现
栏目:php教程时间:2015-04-25 09:37:17
#include<iostream>
using namespace std;
/*
2分查找法
优点:查找速度快,平均性能好。
缺点:待查表为有序表
*/
int main()
{
int binSearch(const int*, int, int, int);
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << binSearch(arr, 0, 9, 5) << endl;
return 0;
}
int binSearch(const int* Array,int start,int end,int key)
{
int left,right;
int mid;
left = start;
right = end;
//注释中为递归算法,履行效力低,不推荐
/*
if(key < Array[mid])
{
return(binSearch(Array, left, mid⑴, key));
}
else if(key > Array[mid])
{
return(binSearch(Array, mid+1, right, key));
}
else
return mid;
*/
while(left<=right)
{
mid = (left+right)/2;
if(key==Array[mid])
{
return mid;
}
else if(key<Array[mid])
{
right=mid⑴;
}
else if(key>Array[mid])
{
left=mid+1;
}
}
return ⑴;
}
------分隔线----------------------------
------分隔线----------------------------