描述
请编写一个递归的折半查找算法,查找给定有序数组中的某一元素。
输入
多组数据,每组数据有三行。第一行为数组长度n,第二行为n个递增排列的数字,第三行为需要查找的数字k。当n=0时输入结束。
输出
每组数据输出一行,如果可以找到数字,则输出“YES”,否则输出“NO”。
样例输入1
5
1 4 6 7 8
6
6
1 2 5 7 9 100
8
0
样例输出1
YES
NO
1 #include<iostream>
2 using namespace std;
3
4 bool binary_search(int arr[], int low, int high, int target)
5 {
6 if (low > high)
7 return false;
8 if (low <= high)
9 {
10 int mid = (low + high) / 2;
11 if (arr[mid] == target)
12 return true;
13 else if (mid < target)
14 {
15 binary_search(arr, mid + 1, high, target);
16 }
17 else
18 {
19 binary_search(arr, low, mid - 1, target);
20 }
21 }
22 }
23
24 int main()
25 {
26 int *arr;
27 int n, target;
28 while (cin >> n)
29 {
30 if (n == 0) break;
31 arr = new int[n + 1];
32 for (int i = 1; i <= n; i++)
33 cin >> arr[i];
34
35 cin >> target;
36 bool flag = binary_search(arr, 1, n, target);
37 if (flag)
38 cout << "YES" << endl;
39 else
40 cout << "NO" << endl;
41 delete[]arr;
42 }
43 return 0;
44 }