Description
给定一递增有序数组a[0,1,...,n-1], 请在数组中搜索给定元素. 搜索过程中请使用mid=(low+high)/2.
Input
第一行输入M表示包含M组测试数据,每组输入N和X, N (1000<=N<=20000) 表示后面有N个整数递增有序数组, 表示将搜索的元素.
Output
搜索成功输出success及父亲, 否则输出not found及父亲.
Sample Input
2
7 10 1 3 5 7 9 11 13
7 10 2 4 6 8 10 12 14
Sample Output
not found, father is 9
success, father is 12
*请注意逗号后加空格
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int n; cin >> n;
int X; cin >> X; bool flag = true;
int arr[20001] = { 0 };
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int left = 0, right = n - 1;
int mid = left + (right - left) / 2; int par = arr[mid];
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] > X )
{
right = mid - 1;
par = arr[mid];
}
else if (arr[mid] < X )
{
par = arr[mid];
left=mid+1;
}
else
{
cout << "success, father is " << par << endl;
flag = false;
break;
}
}
if(flag)
cout << "not found, father is " << par << endl;
}
return 0;
}