题目:
设计一个用于整型数的二分查找的递归函数。
代码:
#include <iostream>
using namespace std;
int search(int a[], int unfound, int left, int right);
int main()
{
int unfound, left, right, n;
cout << "整型数的二分查找(递归实现)" << endl << endl;
cout << "请输入你要保存的数据的数量:";
cin >> n;
int *a = new int[n];
cout << "请按从小到大的顺序输入你要保存的数据:(彼此之间用空格隔开,按回车结束输入)";
for (int i = 0; i < n; ++i) cin >> a[i];
cout << endl << "请输入待查找的数:";
cin >> unfound;
left = 0;
right = n;
if (search(a, unfound, left, right)==0) cout << endl << "查无此数!" << endl << endl;
else cout << endl << "找到此数!" << endl << endl;
system("pause");
return 0;
}
int search(int a[], int unfound, int left, int right)
{
if (left == right) return 0;
else
{
int middle = (left + right) / 2;
if (unfound == a[middle]) return 1;
if (unfound < a[middle])
{
right = middle - 1;
search(a, unfound, left, right);
}
if (unfound > a[middle])
{
left = middle + 1;
search(a, unfound, left, right);
}
}
}