您的位置:首页 > 编程语言 > C语言/C++

《算法导论》4、二分查找实现(C++)

2015-05-07 10:35 295 查看
#include <iostream>
using namespace std;
int binarySearch(int a[], int p, int q, int target);
void main()
{
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
int index=binarySearch(a, 0, 9, 12); //12在数组中不存在
if (index != -1)
cout << a[index] << endl;
else
cout << "error" << endl;
system("pause");
}
int binarySearch(int a[], int p, int q, int target)
{
if (p < q)
{
int temp = (p + q) / 2;
if (a[temp] < target)
binarySearch(a, temp+1, q, target);   //注意+1
else if (a[temp] == target)
return temp;
else
binarySearch(a, p, temp-1, target);   //注意-1
}
else
{
if (a[p] == target)
return p;
else
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: