Please write a recursive binary search algorithm to find an ordered array given an element.
A plurality of sets of data, each set of three rows of data. The first line array length n, the n second ascending behavior number, need to find third row number k. When n = 0, the input end.
Each data output line, if can find a digital, output "YES", and otherwise outputs "NO".
5 1 4 6 7 8 6 6 1 2 5 7 9 100 8 0
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 }