1 #include "stdafx.h"
2 #include <iostream>
3 using namespace std;
//折半查找(非递归调用)
6 bool binarySearch(int *arr,int low,int high,int key)
7 {
8 while (low<=high) {//必须为有=
9 int mid = (low + high) / 2;
10 if (arr[mid] > key) {
11 high = mid - 1;
12 }
13 else if (arr[mid]<key) {
14 low = mid + 1;
15 }
16 else {
17 return true;
18 }
19 }
20 return false;
21 }
23 //折半查找递归调用
24 bool binarySearch(int *arr,int low,int high,int key)
25 {
26 if (low>high) { //递归退出条件
27 return false;
28 }
29 int mid = (low + high) / 2;
30 if (arr[mid]>key) {
31 return binarySearch(arr,low,mid-1,key);
32 }
33 else if(arr[mid]<key){
34 return binarySearch(arr,mid+1,high,key);
35 }
36 else {
37 return true;
38 }
39 }
40
41 //
42 int main()
43 {
44 int arr[10] = {0,1,2,3,4,5,6,7,8,9};
45 int key;//要查找的值
46 cin >> key;
47 bool flag=binarySearch(arr,0,9,key);
48 if (flag) {
49 cout << "查找成功!" << endl;
50 }
51 else {
52 cout << "查找失败!" << endl;
53 }
54 return 0;
55 }