简单二分查找模板(查找)
1 # include <stdio.h> 2 3 int search(int a[], int n, int v) //这个好像是效率最高的 4 { 5 int left = -1, right = n, middle; 6 while(left+1 != right) 7 { 8 middle = left + (right-left) / 2; 9 if(a[middle] < v) 10 left = middle; 11 else 12 right = middle; 13 } 14 if(right >= n || a[right] != v) 15 right = -1; 16 return right; 17 } 18 19 int search1(int a[], int n, int v) 20 { 21 int left = 0, right = n-1, middle; 22 while(left <= right) 23 { 24 middle = (left+right) / 2; 25 if(a[middle] > v) 26 right = middle - 1; 27 else if(a[middle] < v) 28 left = middle +1; 29 else 30 return middle; 31 } 32 return -1; 33 } 34 35 int search2(int a[], int n, int v) 36 { 37 int left = 0, right = n, middle; 38 while(left < right) 39 { 40 middle = (right + left) / 2; 41 if(a[middle] > v) 42 right = middle; 43 else if(a[middle] < v) 44 left = middle + 1; 45 else 46 return middle; 47 } 48 return -1; 49 } 50 51 int a[1000000]; 52 int main(void) 53 { 54 int n, i, t, ans; 55 while(~scanf("%d", &n)) 56 { 57 for(i = 0; i < n; i++) 58 scanf("%d", &a[i]); 59 scanf("%d", &t); 60 ans = search(a, n, t); 61 if(ans <= 0) 62 printf("NO\n"); 63 else 64 printf("YES\n"); 65 } 66 67 return 0; 68 }