# 二分查找算法

1. #include<iostream>
2. using namespace std;
3. int search(int *, int, int);
4. int searchfdg(int *, int, int, int);
5. int search(int *arra, int key, int high) {
6.     int low = 0;
7.     while (low <= high)
8.     {
9.         int mid = (low + high) / 2;
10.           if (arra[mid] == key) {
11.             return mid;
12.          }else if (arra[mid] > key) {
13.             high = mid - 1;
14.          }else
15.             low = mid + 1;
16.     }
17.     cout << "元素不存在！";
18.         return -1;
19. }
20.
21. int searchfdg(int *arra, int key,int low,int high) {
22.
23.         if (low <= high)
24.         {
25.             int mid = (low + high) / 2;
26.             if (key == arra[mid]){
27.                 return mid;
28.             }
29.             else if (key < arra[mid]) {
30.                 return searchfdg(arra, key, low, mid - 1);
31.             }else if (key > arra[mid])
32.                 low = mid + 1;
33.                 return searchfdg(arra, key, mid+1,high);
34.         }
35.         else
36.             cout << "元素不存在！";
37.             return -1;
38.     }
39. int main() {
40.     int arra[] = {3,5,9,14,17,23,29,33,37 };
41.     int size = sizeof(arra) / sizeof(int);
42.     cout << "非递归查找的元素在数组中的位置是：" << endl;
43.     cout << search(arra, 33, size-1) << endl;
44.     cout << "递归查找的元素在数组中的位置是：" << endl;
45.     cout << searchfdg(arra, 33, 0,size-1) << endl; //注意此时的low和high的值
46.
47. }

• 博文量
159
• 访问量
982609