首页 > 代码库 > 简单二分

简单二分

 1 #include <iostream>
 2 
 3 using namespace std;
 4 //upper_bound(a, arr + 10, 7) - a;
 5 int search(int *a, int l, int r, int key)
 6 {
 7     int mid;
 8     while(l <= r)
 9     {
10         mid = (l + r) / 2;
11         if(a[mid] == key) return mid;
12         if(a[mid] < key) l = mid + 1;
13         if(a[mid] > key) r = mid - 1;
14     }
15     return -1;
16 }
17 int upper_bound(int *a, int l, int r, int key)
18 {
19     int mid;
20     while(l <= r)
21     {
22         mid = (l + r) / 2;
23         if(a[mid] <= key) l = mid + 1;
24         if(a[mid] > key) r = mid - 1;
25     }
26     return -1;
27 }
28 
29 int main()
30 {
31     int a[] = {1,2,3,3,4,6,7,7,8,8,9};
32     int l = 0, r = 10;
33     int key;
34     cin >> key;
35     int pos = search(a,l,r,key);
36     cout << "key:" << "a" << "[" << pos << "]" << endl;
37     return 0;
38 }

 

简单二分